简体   繁体   中英

Adding data to a Javascript array of arrays

I'm trying to add data to an array, and getting a weird result.

var arr = [];

var obj1 = { data: ["a","b"]};
var obj2 = { data: ["c","d"]};

arr.push(obj1);
arr[0].data.push(obj2.data);

console.log(arr[0].data);

// 1) what i want: [ ["a", "b"], ["c", "d"] ]
// 2) what i get:  ["a", "b", ["c", "d"] ]

Any idea how can I set it up so that I get the data formatted like: [["a","b"],["c","d"]]? Here's a fiddle for it: http://jsfiddle.net/oakley808/UCQ65/

Try this:

var arr = [];

var obj1 = { data: ["a","b"]};
var obj2 = { data: ["c","d"]};

arr.push(obj1.data);
arr.push(obj2.data);

console.log(arr);

在此处输入图片说明

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM