Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
295 views
in Technique[技术] by (71.8m points)

javascript - best way to generate empty 2D array

is there a shorter, better way to generate 'n' length 2D array?

var a = (function(){ var i=9, arr=[]; while(i--) arr.push([]); return arr })();

a // [ [],[],[],[],[],[],[],[],[] ]

** old-school short-way**:

var a = (function(a){ while(a.push([]) < 9); return a})([]);

UPDATE - Using ES2015

Array(5).fill().map(a=>[]); // will create 5 Arrays in an Array
// or
Array.from({length:5}, a=>[])

Emptying 2D array (saves memory rather)

function make2dArray(len){
    var a = [];
    while(a.push([]) < len); 
    return a;
}

function empty2dArray(arr){
    for( var i = arr.length; i--; )
      arr[i].length = 0;
}

// lets make a 2D array of 3 items
var a = make2dArray(3);

// lets populate it a bit
a[2].push('demo');
console.log(a); // [[],[],["demo"]]

// clear the array
empty2dArray(a);
console.log(a); // [[],[],[]]
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Another way:

for(var a = [];a.length < 10; a.push([])); // semicolon is mandatory here

Yet another way:

var a = []; while(a.push([]) < 10);

This works because .push() [docs] (specification) returns the new length of the array.


That said, this is the wrong way of "reducing code". Create a dedicated function with a meaningful name and use this one. Your code will be much more understandable:

function get2DArray(size) {
    size = size > 0 ? size : 0;
    var arr = [];

    while(size--) {
        arr.push([]);
    }

    return arr;
}

var a = get2DArray(9);

Code is read much more often than written.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

56.9k users

...