我是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);
}
}
}
答案 0 :(得分:1)
您的for loop
条件不正确。用下面的替换。
使用j < i + myName.length
for(var j = i; j < i+myName.length; j++ )
PS: - 有更好的方法,indexOf()
。
答案 1 :(得分: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将返回字符串匹配的位置,如果未找到string,则indexOf返回-1