[英]forEach takes an array and a callback
I need help for this problem because I don't understand it :(. Please help!我需要帮助解决这个问题,因为我不明白:(。请帮忙!
The function forEach takes an array and a callback. forEach 函数接受一个数组和一个回调。 It runs the callback on each element of the array - and that's it!
它在数组的每个元素上运行回调——就是这样!
var alphabet = '';
var letters = ['a', 'b', 'c', 'd'];
forEach(letters, function(char) {
alphabet += char;
});
console.log(alphabet); //prints 'abcd'
**(underneath is is where I edit)**
// Challenge 4
function forEach(array, callback) {
}
// see for yourself if your forEach works!
I do not know exactly what you want to achieve, but your code is not idiomatic JavaScript...我不知道你到底想实现什么,但你的代码不是惯用的 JavaScript ......
The core JavaScript language already provides a forEach
method that you can use directly.核心 JavaScript 语言已经提供了一个可以直接使用的
forEach
方法。 Please read the following page: Array.prototype.forEach()请阅读以下页面: Array.prototype.forEach()
When you use forEach
, your code should look like this:当您使用
forEach
,您的代码应如下所示:
var alphabet = '',
letters = ['a', 'b', 'c', 'd'];
letters.forEach(function (letter) {
alphabet += letter;
});
console.log(alphabet);
But if you are concerned about performance leaks, you may want to use a traditional for
loop with cached length instead.但是,如果您担心性能泄漏,您可能希望改用具有缓存长度的传统
for
循环。
var alphabet = '',
letters = ['a', 'b', 'c', 'd'];
for(var i = 0, len = letters.length; i < len; i++) {
alphabet += letters[i];
}
console.log(alphabet);
Thanks to ES6, you can also use the for...of
loop on iterable objects like arrays.感谢 ES6,您还可以在可迭代对象(如数组)上使用
for...of
循环。 This is the recommended instruction in modern JavaScript applications:这是现代 JavaScript 应用程序中的推荐指令:
let alphabet = '',
letters = ['a', 'b', 'c', 'd'];
for (const letter of letters) {
alphabet += letter;
}
console.log(alphabet);
But since developers are lazy sometimes, the best answer is probably this one:但由于开发人员有时很懒惰,最好的答案可能是这个:
var letters = ['a', 'b', 'c', 'd'],
alphabet = letters.join('');
console.log(alphabet);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.