Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

Hi I want to use nested arrays in my javascript function but it doesn't work. Here is my function:

var arr = [];

function test(id, value){
   arr.push(new Array("id" = id, "value" = value));
}

so as you find out I want to create something like this:

arr[0][id = "example0", value = "value0"];
arr[1][id = "example1", value = "value1"];
arr[2][id = "example2", value = "value2"];
...
share|improve this question

2 Answers

up vote 9 down vote accepted

Because new Array("id" = id, "value" = value) is not an array.

You want an array holding an object.

arr.push({"id":id, "value":value});

Read values

console.log(arr[0].id);
share|improve this answer

You should create an array of objects, then you reference their properties.

var arr = [];

function test(id, value){
     arr.push({"id":id,"value":value});
}


function getValue(i)
{
     return arr[i].value;
}

test(100,"hello");
test(101,"world");

alert(getValue(0)); // hello
alert(getValue(1)); // world
alert(arr[1].id); // 101
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.