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


这是为了将text [i] [2]中字符串的单词计数推到text [i] [3]。我已经检查了一下,最接近问题的是if语句的条件...但是看起来不错。
问题:为什么它不起作用?

最佳答案

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

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

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


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

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


您还可以使用charAt方法来获取字符,这看起来更自然:

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


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

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

关于javascript - for循环内的for循环内的if语句-不满足条件,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23584991/

10-09 15:04