JQuery: utility functions VIII – creating arrays from other objects

Published Mon, Aug 10 2009 14:30

The utility function makeArray is a helper which is used internally by JQuery to transform collections of nodes into arrays. Even though this function is “public”, you’re not expected to use it much. Here’s its current internal implementation:

makeArray: function( array ) {
    var ret = [];
    if( array != null ){
        var i = array.length;
        // The window, strings (and functions) also have 'length'
        if( i == null || typeof array === "string" || jQuery.isFunction(array) || array.setInterval )
            ret[0] = array;
        else
            while( i )
                ret[--i] = array[i ];
    }
    return ret;
}

As you can see, the code function starts by getting the length and checking the current type of the array parameter. If you’re passing a function (isFunction helper), a string, a window object or if the length doesn’t exist, you’ll end getting an array with a single element.

In the remaining scenarios, you’ll go through all the elements in the array and you’ll copy them to an array. Notice that in Javascript it’s possible to have an object which isn’t an array but that does behave like one. Let me present a simple example of this:

var arr = (function() {
return $.makeArray(arguments); })(1, 2, 3);

So, what I’m doing here? Simple: I’m creating and executing an anonymous function and saving the returned result on the arr variable. The anonymous function will pass arguments to the makeArray function and you’ll get back a “real” array. If you debug the previous code, you’ll see that arguments behaves like an array but it’s not an array:

debugarguments

As you can see, the arguments object has indexes and you even have a length property. However, things stop working if you try to use a method that exists on arrays. For instance, if you use the push method, you’ll end up getting an exception.

The node lists which you get back from the methods like getElementsByTagName behave like arrays but aren’t really arrays. In those cases, you can easily get an array by using this utility function. And that’s all for this post. Keep tuned for more on JQuery.

Filed under:

Comments

# 9eFish said on Monday, August 10, 2009 8:42 PM

9efish.感谢你的文章 - Trackback from 9eFish

# cloudgen said on Wednesday, August 19, 2009 4:03 AM

Thanks for your sharing

Leave a Comment

(required) 
(required) 
(optional)
(required)