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.
![9 Mind-Blowing Canvas Demos]()
The <canvas> element has been a revelation for the visual experts among our ranks. Canvas provides the means for incredible and efficient animations with the added bonus of no Flash; these developers can flash their awesome JavaScript skills instead. Here are nine unbelievable canvas demos that...
![5 More HTML5 APIs You Didn’t Know Existed]()
The HTML5 revolution has provided us some awesome JavaScript and HTML APIs. Some are APIs we knew we've needed for years, others are cutting edge mobile and desktop helpers. Regardless of API strength or purpose, anything to help us better do our job is a...
![MooTools PulseFade Plugin]()
I was recently driven to create a MooTools plugin that would take an element and fade it to a min from a max for a given number of times. Here's the result of my Moo-foolery.
The MooTools JavaScript
Options of the class include:
min: (defaults to .5) the...
![Custom Scrollbars in WebKit]()
Before each of the browser vendors we like was providing unique CSS controls, Internet Explorer was setting the tone. One such example is IE's early implementation of CSS filters. Internet Explorer was also the first browser that allowed developers to, for better or worse, customize...
If you’re using Firefox, or in the future when other browsers support ES6, you can do it more elegantly:
function myFn(...args) { /* code */ }In case you are using Mootools,
Array.fromdoes the job, isn’t it ?Why not it:
You can do that but be aware if you do something like:
function x(){ return Array.apply(null, arguments); }; x(10); //=> it will return empty array with a length of 10 instead of [10]Cool trick, but why even
typeof argumentsreturnsobject?We have a new method,
Array.from(arguments)