2015-02-23 67 views
0

我是JavaScript的新手,並在下面的代碼中找到字符串「Craig」並將其推入新的數組「Hits」中。無法將某些字符串插入到數組中

var text = "Hey, how are you \ doing? My name is Emily.\ My other friends  name is Craig. My friend Craig is learning JavaScript"; 
var myName = "Craig" 
var hits = []; 

for(var i = 0; i < text.length; i++){ 
if(text[i]=== "C"){ 
    for(var j = i; j < myName.length; j++){ 
     hits.push(j); 
    } 
} 
} 

回答

1

for loop條件是不正確的。用下面的代替它。 使用j < i + myName.length

for(var j = i; j < i+myName.length; j++) 

PS: - 有更好的方式來做到這一點,indexOf()

0
var text = "Hey, how are you \ doing? My name is Emily.\ My other friends name is Craig. My friend Craig is learning JavaScript"; 

    var myName = "Craig" 
    var hits = []; 

    if (str.indexOf("Craig") > -1) 
    { 
     hits.push(myName); 
    } 

這裏的indexOf將返回字符串匹配的位置,如果字符串沒有找到,則IndexOf返回-1

+0

謝謝你的提示雲。 – 2015-02-23 04:35:28

相關問題