Asim Zaidi
Asim Zaidi

Reputation: 28284

why this not adding to array

I am trying to create a multidimenssional array like this

var myArray = new Array();
          var test = new Array(1, 100,200,2);
        $.each(test, function(index, val) {

            myArray['value'].push(val);
            myArray['index'].push(index);
        });

but console.log(myArray) shows me no values;

Upvotes: 0

Views: 61

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

Use an object literal instead of an array:

var myHash= {
    value: [],
    index: []
},
test = [1, 100,200,2];

$.each(test, function(index, val) {
    myHash['value'].push(val);
    myHash['index'].push(index);
});

You shouldn't use arrays as associative arrays. Arrays are accessed by 0-based index and you shouldn't assign arbitrary properties to arrays.

Example: http://jsfiddle.net/andrewwhitaker/F7Zx5/

Upvotes: 2

Related Questions