javascript - Codecademy JavaScript Push() 练习

标签 javascript arrays

CodeAcademy 的目标尚不明确。 http://bit.ly/167N8bX 我认为应该遍历一个长字符串,并将我名字的字符从字符串中推出到一个数组中。

其表述如下:

"it will check the text for the first letter of your name, then push (add) the number of characters equal to your name's length to an array. By inspecting the array, you'll be able to see if your name was mentioned!"

*已更新。现在我看到了讲师的输出,它实际上并没有检查您的名字是否被提及。对于像我这样的新手来说,指令令人困惑。

我正在进行 7 步中的第 5 步:链接:http://bit.ly/167N8bX

var text = "Lorem ipsum dolor nayr sit amet, consectetur adipisicing elit, sed do eiusmod tempor yan ut Ryan labore et dolore magna aliqua. Ut enim ad ry minim veniam, quis nostrud ryan exercitation ullamco ryan laboris nisi ut aliquip ex ea ry commodo rya consequat. END";
var myName = "Ryan";
var hits = [];

for(var i = 0; i < text.length; i++) {
    // Loop thru "text" string
    // check each char one-by-one
    // if it finds uppercase "R"
    if(text[i] == "r".toUpperCase()){

    // push the next 3 chars into hits[] array...
    // by looping on myName.length
    // end push() when myName.length loops ends
       for(var j = 0; j < myName.length; j++){
           hits.push(text[i]);
           console.log(hits);
       }
    }
}

*已更新 如何防止每个循环出现输出,并将每次推送存储在数组中,直到完成所有循环?

上面代码的错误输出:

[ 'R' ]
[ 'R', 'y' ]
[ 'R', 'y', 'a' ]
[ 'R', 'y', 'a', 'n' ]

最佳答案

我认为问题在于,在你的内部循环中,你每次只推送相同的字母。您需要将其修改为以下内容:

hit.push(text[i + j])

这应该可以解决问题。祝您继续编码顺利!

关于javascript - Codecademy JavaScript Push() 练习,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19338243/

相关文章:

javascript - 在不使用 Jquery 推送其他图像的情况下,在鼠标悬停时放大图像?

javascript - typescript 的 Node.js process.stdin 问题(tty.ReadStream 与 ReadableStream)

javascript - Angular .js : two-way binding inside ng-repeat

javascript - 使用 Jasmine 测试 Angular Controller 中的对象初始化

javascript - AngularJS 使用 UI Router 进行翻译

c - 打印语句更改字符数组输出

JavaScript,组合数组中的匹配元素

c - C 中的蛮力 for 3Sum - 但我如何检测重复的三胞胎?

arrays - Go中的JSON解码有符号整数数组

javascript - 无法理解为什么使用展开运算符