使用JavaScript循环问题,将值插入数组将不起作用

时间:2013-12-13 20:10:13

标签: javascript arrays loops

/*jshint multistr:true */
var myName = "Killa";
var text = "Blah blah blah blah blah blah Killa \
blah blah blah Killa blah blah Killa blah blah \
blah blah blah blah blah Killa";
var hits = [];
for (var i = 0; i > text.length; i++){
    if (text[i] == "K"){
        for (var j = i; j < (i + myName.length); j++){
            hits.push(j);
        }
    }
}

为什么killa不会被推入Hits数组。请帮我。出于安全目的更改了文本。对不起,如果它看起来很傻。

2 个答案:

答案 0 :(得分:6)

i > text.length应该是i < text.length

答案 1 :(得分:1)

下面的代码修复了您的问题并将“Killa”添加到数组Hits。

var myName = "Killa";
var text = "Blah blah blah blah blah blah Killa \
blah blah blah Killa blah blah Killa blah blah \
blah blah blah blah blah Killa";
var hits = [];
for (var i = 0; i < text.length; i++){
    if (text[i] == "K"){
        for (var j = i; j < (i + myName.length); j++){
            hits.push(text[j]);
        }
    }
}


    console.log(hits);