2015-11-14 60 views
0

在你看我的問題之前請注意我是一個新手,我目前正在通過codecademy JavaScript課程,但我非常堅持這一點,這可能看起來很愚蠢一些。試圖讓我的頭與週期鏈接的東西。Javascript - 將字符從字符串推到數組使用for循環

試圖將字符串中的所有字符從字符串中推送到數組「命中」。

我真的很感激一些指導。

var text = "hi it's raheel that's right raheel did i mention it's raheel it actually is raheel" 
 

 
var myName = "raheel" 
 

 
var hits = [] 
 

 
for (var i = 0; i < text.length; i++); { 
 

 
    if (text[i] === "r") { 
 

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

+0

1)當推動命中時,你有一個額外的')'。 2)'if(text [i] ===「r」)'也會匹配單詞'right' – AdamJeffers

回答

0

如果我理解你的權利......我不是100%地確信我做你應該看看這樣的事情...

var text = "hi it's raheel that's right raheel did i mention it's raheel it actually is raheel"; 
var myName = "raheel"; 
var words = text.split(' '); 
var hits = []; 

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

console.log(hits); 

然而,這會多次推送匹配的myName,所以給定您的文本,該數組將包含4個「raheels」。

["raheel", "raheel", "raheel", "raheel"] 
相關問題