Monday, June 25, 2012

jQuery makeArray And Array Lengths

Today I just came to know about a pretty cool thing when i was going through the documentation of the jQuery.map function. Now, the jQuery makeArray function is pretty useful because it can convert objects into arrays. But there is one restriction, your objects need to be array like objects. And what are array like objects? Array like objects are objects that have a length property. And I think that it would be safe to presume that he most common array like object known to mankind is the arguments object that is available in javascript functions.

Well, arrays in JavaScript are pretty cool because you can just remove elements from the end of an array by doing a very simple thing. Modifying the length property of the array. For example, lets say that you have an array

var myArray = [1,2,3,4,0,0,0];


Now you want to keep only the first four elements. What do you do? You simply change the lenght of the array to 4. And voila you're done. While that's cool, I was hoping that if you want to delete elements from the beginning of the array, you could set the length to a negative value. But sadly, that does not work :(. Well, you could always resolve to the good ol technique of using the shift() function. Or you could choose to reverse() and then pop(). Depends on your requirement.

But the interesting thing was that when using the makeArray function, if the length property is not set to a proper value, you will end up with an incorrect array. Taking this example right from the jQuery documentation page for the map function


// The following object masquerades as an array.
var fakeArray = {"length": 1, 0: "Addy", 1: "Subtracty"};

// Therefore, convert it to a real array
var realArray = $.makeArray( fakeArray )

// Now it can be used reliably with $.map()
$.map( realArray, function(val, i) {
  // do something 
});


As you see the fakeArray has a lenght property set to 1. When you invoke makeArray, you get an array containing only 1 element - [Addy]. What just happened to the second element??? It seems that the makeAray function converts the object into an array only for 'length' number of elements. Hence, when using this function, just beware of this behaviour and make sure that the lenght property is equal to the number of properties in your object (not counting the lenght property itself), or you might just be in for a little surprise! 

Signing Off
Ryan Sukale

No comments: