Javascript JSONArray issue with push() and for loop

I've made a simple program to store locally an array using two for loops, but something strange took place...

There's my code:

var imagesdata = data[0];
var preferences = data[1];

for (var i = preferences.length - 1; i >= 0; i--) {
    (function(i){
        for (var z = imagesdata.length - 1; z >= 0; z--) {
            (function(i){
                if(imagesdata[z].cathegory == preferences[i].cathegory){
                    var array = $('body').data('data'+preferences[i].cathegory);
                    if(array == null){
                        alert('asefsef');
                        $('body').data('data'+preferences[i].cathegory, [{'pname' : imagesdata[z].pname , 'pimage' : imagesdata[z].pimage}]);
                    }else{
                        $('body').data('data'+preferences[i].cathegory, array.push({'pname' : imagesdata[z].pname , 'pimage' : imagesdata[z].pimage}));
                    }
                }
            })(i);
        };
    })(i);
};

It says that object 2 has no method push But why number two appears on the array if I've just inserted : [{'pname' : imagesdata[z].pname , 'pimage' : imagesdata[z].pimage}]

Thanks!

push() returns the length of the array, not the array with the new element tacked on.

Unless I'm mis-reading your code:

  1. In the first iteration, you're hitting the == null check, and so creating a new array.
  2. In the second iteration, you're in the else clause and adding an element to the array, but then setting the data property to it's length (2).
  3. In the third iteration, a Number does not have a push() method.

However, note that because the array variable will be a reference to the array once you've initialized the array, all changes you make to it will automagically be reflected back in the data property; so you don't need to write back the changes when you push() new data:

if (array == null) {
    alert('asefsef');
    $('body').data('data' + preferences[i].cathegory, [{
        'pname': imagesdata[z].pname,
        'pimage': imagesdata[z].pimage}]);
} else {
    array.push({
        'pname': imagesdata[z].pname,
        'pimage': imagesdata[z].pimage
    });
}​

FYI, you're probably only hitting the == null check by luck. data() returns undefined if the key doesn't exist, and it just so happens undefined == null is true (through type coercion). A better check would be === undefined, or better yet, array instanceof Array