产生空二维数组最好的方法 [英] best way to generate empty 2D array

查看:96
本文介绍了产生空二维数组最好的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一个较短的,更好的方法来生成'N'长二维数组?

  VAR一个=(函数(){VAR I = 9,编曲= [];而(我 - )arr.push([]);返回ARR})() ;一个 // [ [],[],[],[],[],[],[],[],[] ]

更新 - 现在最短的路

  VAR一个=(函数(){而(a.push([])10 9);返回})([]);

更新 - 使用ES6

 阵列(5).fill伪()图(()=> []); //将在阵列中创建5阵列

清空二维数组(节省内存,而不是重新创建另一:

 函数make2dArray(LEN){
    变种一个= [];
    而(a.push([])LT; LEN);
    返回;
}功能empty2dArray(ARR){
    对于(VAR I = arr.length;我 - ;)
      改编[I]。长度= 0;
}//可以使3个元素的二维数组
变种一个= make2dArray(3);//使填充有点
A [2] .push('示范');
的console.log(一); // [[],[],[演示]//清除数组
empty2dArray(一);
的console.log(一); // [] [] []


解决方案

另一种方式:

 为(VAR A = [];则为a.length小于10; a.push([])); //分号是强制性这里

另一种方式:

  VAR一个= [];而(a.push([])小于10);

这工作,因为<一href=\"https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/push\"><$c$c>.push() [文件] 的(规范)返回数组的新长度。


这是说,这是减少code走错了路。创建一个有意义的名字专门的功能,并使用这一个。您code将变得更加可以理解的:

 函数get2DArray(大小){
    大小=&GT; 0?大小:0;
    VAR ARR = [];    而(size--){
        arr.push([]);
    }    返回ARR;
}变种一个= get2DArray(9);

code得多往往比所写。

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 // [ [],[],[],[],[],[],[],[],[] ]

UPDATE - shortest way for now is:

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

UPDATE - Using ES6

Array(5).fill().map(()=> []); // will create 5 Arrays in an Array

Emptying 2D array (saves memory rather than re-creating another:

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); // [[],[],[]]

解决方案

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.

这篇关于产生空二维数组最好的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆