如果for循环中的for循环内的语句 - 条件不满足

时间:2014-05-10 18:50:16

标签: javascript

var text = [["1","1.","The Wagner diatribe and 'The Twilight of the Idols' were published"],["2","2.","suspect that the delay was due to the influence of the philosopher's"],["3","3.","bounds were marked by crosses. One notes, in her biography of him--a"]];

var amountOfTexts = text.length;
var tempArray = [];
for(var i=0; i<amountOfTexts; i++){
    tempArray = [];
    var current = text[i][2];
    var x = current.length;
    for(var j=0; j<x; j++){
        var y = j+1;
        if(current.substr(j,y) === " "){
            tempArray.push("counter");
        }
    }
console.log(tempArray.length);
    var nearlyWords = tempArray.length;
    var words = 1+nearlyWords;
    text[i].push(words);
}

打印到控制台:

0
0
1

我期待的地方:

11
12
12

它意味着将文本[i] [2]中字符串的字数推到文本[i] [3]。

我已经检查了它,并且最接近问题的是if语句的条件......但它们似乎很好。

问题:为什么它不会起作用?

2 个答案:

答案 0 :(得分:1)

您使用的substr方法错误,它不会采用与substring方法相同的参数。

使用substr并将长度指定为第二个参数:

if (current.substr(j, 1) === " ") {

或将substring与您当前的参数一起使用:

if (current.substring(j, y) === " ") {

你也可以使用charAt方法来获得一个看起来更自然的角色:

if (current.charAt(j) === " ") {

在较新的浏览器(IE 8及更高版本)中,您还可以使用括号语法获取字符:

if (current[j] === " ") {

答案 1 :(得分:0)

你可以使用current.charAt(j)===“”它会更合适,这里是代码

for(var i=0; i<amountOfTexts; i++){
    ...

    for(var j=0; j<x; j++){
        var y = j+1;
        if(current.charAt(j) === " "){
            tempArray.push("counter");
        }
    }

   ...
}
相关问题