Convert arguments to Array
The arguments
object thats automatically available within functions can be a source of confusion for some people; it's kind of an array but it's kinda not. JavaScript is awesome in that you can pass any number of arguments
to a function, and oftentimes developers need to iterate over every argument provided. The arguments
object doesn't have a forEach method, but using a quick JavaScript technique, you can convert arguments
to an array:
function myFn(/* any number of arguments */) {
var args = Array.prototype.slice.call(arguments);
// or [].slice.call(arguments)
args.forEach(function(arg) {
// do something with args here
});
}
Much like converting a NodeList to an array, Array's slice
method takes the arguments
object and converts it to a true array, allowing for forEach, map, and traditional array iteration. Keep that trick up your sleeve for future development.
Two years ago I documented my struggles with Imposter Syndrome and the response was immense. I received messages of support and commiseration from new web developers, veteran engineers, and even persons of all experience levels in other professions. I've even caught myself reading the post...
With CSS border-radius, I showed you how CSS can bridge the gap between design and development by adding rounded corners to elements. CSS gradients are another step in that direction. Now that CSS gradients are supported in Internet Explorer 8+, Firefox, Safari, and Chrome...
Providing users as many preferences as possible always puts a smile on the user's face. One of those important preferences is font size. I can see fine but the next guy may have difficulty with the font size I choose. That's why...
One thing I love doing is duplicating OS functionalities. One of the things your OS allows you to do easily is move from one item to another. Most of the time you're simply trying to get to the next or the previous item.
If you’re using Firefox, or in the future when other browsers support ES6, you can do it more elegantly:
In case you are using Mootools,
Array.from
does the job, isn’t it ?Why not it:
You can do that but be aware if you do something like:
Cool trick, but why even
typeof arguments
returnsobject
?We have a new method,
Array.from(arguments)