简体   繁体   中英

Not Able to Push Arrays into Array (Making Array of Arrays)

can you please take a look at this snippet and let me know why I am not able to create an array of array at this example?

 var data1 = [5555,22,102858,12,.554,88888,99999999,12,1.5]; var data2 = [5555,22,102858,12,.554,88888,99999999,12,1.5]; var data3 = [5555,22,102858,12,.554,88888,99999999,12,1.5]; var data4 = [5555,22,102858,12,.554,88888,99999999,12,1.5]; var all = []; all[0].push(data1); all[1].push(data2); all[2].push(data3); all[3].push(data4); var myJsonString = JSON.stringify(all); console.log(myJsonString); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 

You should be doing all.push(dataX) since all[X] is undefined .

var data1 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data2 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data3 = [5555,22,102858,12,.554,88888,99999999,12,1.5];
var data4 = [5555,22,102858,12,.554,88888,99999999,12,1.5];

var all = [];
all.push(data1);
all.push(data2);
all.push(data3);
all.push(data4);

var myJsonString = JSON.stringify(all);
console.log(myJsonString);

Explanation:

In the code you wrote, all is an empty Array .

all[X] (eg all[0] ) refers to the first element of the array, which doesn't exist (since array is empty). JavaScript interprets this as undefined . (There is no array out of bounds exception)

undefined has no method .push(...) which is why your code is failing.

What you want is to call all.push(...) where you're calling .push(...) on the all Array .

all[0].push(data1);

all[0] retrieves the first element of all . Since you just made the array and it's empty, this is undefined . (In other languages, it would be an array index access violation). You're then trying to push onto that first element; if it were an array itself, this would give you [[[5555,22,... which is one more array container than you want.

Easiest solution is to construct the array via a literal.

var all = [data1, data2, data3, data4];
// no "push()" necessary here.

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