Converting Function Arguments into an Array
Problem
You want to use Array functionality on a function’s arguments, but the arguments object isn’t an array.
Solution
Use Array.prototype.slice() and then the function call() method to convert the
arguments collection into an array:
function someFunc() { var args = Array.prototype.slice.call(arguments); ... }Or, here’s a simpler approach:
function someFunc() {
var args = [].slice.call(arguments);
}
EXPLAIN
The arguments object is available within a function (and only available within a func‐ tion) and is an array-like object consisting of all arguments passed to the function. I say “array like” because the only Array property available to the object is length.
There could be any number of times when our function may get an unknown number of arguments and we’re going to want to do something with them, such as iterate over the batch and perform some process. It would be nice to be able to use a handy Array method like reduce() with the arguments:
function sumRounds() { var args = [].slice.call(arguments); return args.reduce(function(val1,val2) { return parseInt(val1,10) + parseInt(val2,10); }); } var sum = sumRounds("2.3", 4, 5, "16", 18.1); console.log(sum); // 45
The slice() method returns a shallow copy of a portion of an array, or all of an array if a begin or ending value is not given. The slice() method is also a function, which means functional methods like call() can be used with it. In the code snippet, call() is passed the function arguments, which performs the necessary conversion on the argument list, passing in the resulting array to slice().
The call() method’s first argument is a this value—typically the calling object itself, followed by any number of arguments. In the solution, this is the slice() method, and the outer function’s arguments are passed as arguments for slice(). What this technique has effectively done is coerce the outer function’s arguments into an accept‐ able format to serve as argument for slice().
The approach described for converting arguments into an array can also be used to convert a NodeList into an array. Given HTML with the following
onvert a NodeList into an array. Given HTML with the following:A query for all div elements results in a NodeList. You can process each node using forEach() if you first convert the NodeList to an array:testtest2test3
var nlElems = document.querySelectorAll('div'); var aElems = [].slice.call(nlElems); aElems.forEach(function(elem) { console.log(elem.textContent); });
This code prints out:
test test2 test3
No comments:
Post a Comment