[i]Learn· Indexed collections
Working with array-like objects
Some JavaScript objects, such as the NodeList returned by document.getElementsByTagName() or the arguments object made available within the body of a function, look and behave like arrays on the surface but do not share all of their methods. The arguments object provides a length attribute but does not implement array methods like forEach().
Array methods cannot be called directly on array-like objects.
function printArguments() {
arguments.forEach((item) => {
console.log(item);
}); // TypeError: arguments.forEach is not a function
}
But you can call them indirectly using Function.prototype.call().
function printArguments() {
Array.prototype.forEach.call(arguments, (item) => {
console.log(item);
});
}
Array prototype methods can be used on strings as well, since they provide sequential access to their characters in a similar way to arrays:
Array.prototype.forEach.call("a string", (chr) => {
console.log(chr);
});example 1 of 3
[>_]Terminal
Output appears here when you press Run.
$ ▌