Javascript - 使用for循环将字符从字符串推送到数组

时间:2015-11-14 18:48:43

标签: javascript arrays loops for-loop push

在你看我的问题之前,请注意我是一个新手,我目前正在完成codecademy 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))
}
}
&#13;
&#13;
&#13;

1 个答案:

答案 0 :(得分: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"]