简体   繁体   中英

How can i push an array to another array to make a 2 level array?

it might sound confusing though my goal is to make an array like this.

var array2D= [
    { locations: [0, 0, 0], status: ["", "", ""] },
    { locations: [0, 0, 0], status: ["", "", ""] },
    { locations: [0, 0, 0], status: ["", "", ""] }
],

so consider if i have arrays like below.

var locations = [0,0,0];
var status = ["","",""]; 

can i somehow push them to make a 2d array? i tried something like this but it doesn't work

var the2Darray =[];
the2Darray.push(location,status);
var locations = [0,0,0];
var status = ["","",""]; 
var the2Darray =[];
the2Darray.push({locations: locations,status: status});

You have to create an object with keys as locations and status assigning them corresponding array, then simply push to your new array.

var 2dArray = [];
for(var i = 0; i < lengthYouWant; i++) {
    var locations = [1,2,3];
    var status = ["a", "b", "c"];
    var obj = {locations : locations, status : status};
    2dArray.push(obj);
}

Assuming, you want independent arrays, than you need to use Array#slice for a copy of primitive types , like string, number, boolean, null, undefined, symbol (new in ECMAScript 2015).

 var locations = [0, 0, 0], status = ["", "", ""]; array = [], l = 3; while (l--) { array.push({ locations: locations.slice(), status: status.slice() }); } array[2].locations[0] = 42; console.log(array) 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

What happpens, if not using splice, please have a look to 42 .

As you will see, all arrays of locations and status shares the same reference to the original array.

 var locations = [0, 0, 0], status = ["", "", ""]; array = [], l = 3; while (l--) { array.push({ locations: locations, status: status }); } array[2].locations[0] = 42; console.log(array) 
 .as-console-wrapper { max-height: 100% !important; top: 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