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.
-
One of the worst kept secrets about AJAX on the web is that the underlying API for it, XMLHttpRequest
, wasn't really made for what we've been using it for. We've done well to create elegant APIs around XHR but we know we can do better. Our effort to...
-
Back in late 2012 it was not easy to find open source projects using requestAnimationFrame()
- this is the hook that allows Javascript code to synchronize with a web browser's native paint loop. Animations using this method can run at 60 fps and deliver fantastic...
-
Remember the Web 1.0 days where you had to customize your site in every way possible? You abused the scrollbars in Internet Explorer, of course, but the most popular external service I can remember was CometCursor. CometCursor let you create and use loads of custom cursors for...
-
CSS class name structure and consistency is really important; some developers camelcase classnames, others use dashes, and others use underscores. One thing I've learned when toying around by HTML and CSS class names is that you can actually use unicode symbols and icons as classnames.
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)