[英]If statement within a for loop within a for loop - condition isn't being met
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] === " ") {
您可以使用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");
}
}
...
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.