简体   繁体   中英

JavaScript 2-Dimensional Array.push()

When pushing:

a=[ ['','','','','','','',''] ];
a.push("['','','','','','','','']");

or

a=[ ['','','','','','','',''] ];
a.push(new Array(8));

I want to get:

a=[ ['','','','','','','',''], ['','','','','','','',''] ];

as a result, but instead, I get:

a= [ ['','','','','','','',''], '','','','','','','','' ];

I ONLY want ONE element added (with 8 sub-elements inside). Instead, I now have 9 elements. it's messing with my array.length values, as you could imagine!

I understand that:

a.push('','','','','','','','');

will add the 8 extra elements as if I pushed each one separately.

even I tried:

EmptyData=['','','','','','','',''];
a.push(EmptyData);

and STILL got 8 elements added. what am I doing wrong?

Short solutions or jsfiddle would be a wonderful holiday gift.

a.push("['','','','','','','','']"); you are pushing a string "..." , not an array

This will work fine:

a=[ ['','','','','','','',''] ];
a.push(['','','','','','','','']);

You can use this trick to create a normal array of N elements:

var arr_of_n_elements = Array.apply(null, Array(n));

To create an mxn array, just use this trick twice:

var m_n_arr = Array.apply(null, Array(n)).map(function() {
   return Array.apply(null, Array(m));
});

With this approach, each element of this array will be undefined (but it'll be a proper array - iterable, etc. - otherwise). To use a specific value, just add another - filler - map :

var empty_val = '';
var m_n_arr = Array.apply(null, Array(m)).map(function() {
   return Array.apply(null, Array(n)).map(function() {
     return empty_val;
   });
}); 

If your target platform supports Array.prototype.fill() , it gets even more concise:

var m_n_arr = Array.apply(null, Array(n)).map(function() {
   return Array(m).fill(empty_val);
});

Do not fall into the trap of oversimplification: this...

var m_n_arr = Array(n).fill(Array(m).fill(empty_val));

... will create an array of exactly the same objects. Now, when you change the value in one row:

m_n_arr[0][0] = '42';

... it means all the elements of 0-th column become equal to '42' too. And that's hardly what you want to see. )

Solution for any length:

 var a = [['', '', '', '', '', '', '', '']]; a.push(Array.apply(null, { length: 8 }).map(function () { return ''; })); document.write('<pre>' + JSON.stringify(a, 0, 4) + '</pre>'); 

For best practice you should assign the other array as a variable.

var x = [ ['', '', '', '', ''] ],

y = ['', '', '', ''];

x.push(y);

console.log(x);

This will return [ [ '', '', '', '', '' ], [ '', '', '', '' ] ]

Here is a repl for it https://repl.it/BaQT/0

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