I need help for this problem because I don't understand it :(. Please help!
The function forEach takes an array and a callback. 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...
The core JavaScript language already provides a forEach
method that you can use directly. Please read the following page: Array.prototype.forEach()
When you use forEach
, your code should look like this:
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.
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. This is the recommended instruction in modern JavaScript applications:
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);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.