2017-04-13 53 views
0

任何帮助将不胜感激:我只是不能继续前我弄清楚我做错了什么..搜索文本的名称(javascript)

我正在寻找一个文本名称与一个for循环,然后试图将这些字母推入数组。出于某种原因,这不是推动,我不知道我在做什么错误..仍然是一个新手.. thx的帮助!

var text = "Code it out bro, it will just get Zane Zane Zane better 
from here, especially after your familiar with the various 
frameworks..yeah man..."; 
var hits = [ ]; 
var nameZane = "Zane"; 
for (i=0; i < text.length; i++) 
if (i === "Z"){ 
    for (j=i; j < nameZane.length + i; j++){ 
    hits.push(text[j])} 
} 

if (hits.length === 0){ 
    console.log("Couldn't find " + nameZane)} 
else{ 
    console.log(hits)} 
+1

何必太多这样做。只要使用正则表达式这个 –

+0

将'i ===“Z”'永远是_true_? – Satpal

+1

它应该是'text [i] ===“Z”' – gurvinder372

回答

0

是不是i其一个text[i]利用这个条件,如果像这样if (text[i] === "Z") {

var text = "Code it out bro, it will just get Zane Zane Zane better from here, especially after your familiar with the variousframeworks..yeah man..."; 
 
var hits = []; 
 
var nameZane = "Zane"; 
 
for (i = 0; i < text.length; i++) 
 
    if (text[i] === "Z") { 
 
    for (j = i; j < nameZane.length + i; j++) { 
 
     hits.push(text[j]) 
 
    } 
 
    } 
 

 
if (hits.length == 0) { 
 
    console.log("What the f*** man?") 
 
} else { 
 
    console.log(hits) 
 
}

+0

只是一个小的优化。在'if'里面'for'后,你可以做'i + = nameZane.length'。这将删除不需要的迭代 – Rajesh

0

编辑代码:
if (i === "Z")

if (text.charAt(i) == 'Z') 

hits.push(text[j]) 

hits.push(text.charAt(j)); 
0
var re = /Zane/g, 
str = "Code it out bro, it will just get Zane Zane Zane better from here, especially after your familiar with the various frameworks..yeah man..."; 
while ((match = re.exec(str)) != null) { 
    console.log("match found at " + match.index); 
}