如何在 JavaScript 中创建一个由零组成的二维数组?

发布于 2024-09-18 07:50:40 字数 156 浏览 1 评论 0原文

有没有一种简单的方法可以在 JavaScript 中以编程方式创建二维数组?

我不想要什么:

var array2D = [ 
  [0,0,0],
  [0,0,0],
  [0,0,0]
]

Is there an easy way to programmatically create a 2d array in javascript?

What I don't want:

var array2D = [ 
  [0,0,0],
  [0,0,0],
  [0,0,0]
]

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

放飞的风筝 2024-09-25 07:50:40

2017 年解决方案:

虽然迟到了,但这篇文章在 Google 搜索结果中的排名仍然很高。

要创建给定大小的二维数组(可适应更多维度):

let array = Array(rows).fill().map(() => Array(columns));

预填充二维数组:

let array = Array(rows).fill().map(() => Array(columns).fill(0));

例如:

Array(2).fill().map(() => Array(3).fill(42));
// Result:
// [[42, 42, 42],
//  [42, 42, 42]]

警告:

Array(rows).fill(Array(columns)) 将导致所有行都是对同一数组的引用!

2018 年 9 月 24 日更新(感谢 @Tyler):

另一种可能的方法是使用 Array.fill() 来应用地图函数。

例如:

Array.from(Array(2), _ => Array(3).fill(43));
// Result:
// [[43, 43, 43],
//  [43, 43, 43]]

基准:

https://jsperf.com/multi-Dimension-array -map-vs-fill/5

Solution 2017:

Late to the Party, but this Post is still high up in the Google search results.

To create an empty 2D-Array with given size (adaptable for more dimensions):

let array = Array(rows).fill().map(() => Array(columns));

Prefilled 2D-Array:

let array = Array(rows).fill().map(() => Array(columns).fill(0));

E.g.:

Array(2).fill().map(() => Array(3).fill(42));
// Result:
// [[42, 42, 42],
//  [42, 42, 42]]

Warning:

Array(rows).fill(Array(columns)) will result in all rows being the reference to the same array!!

Update 24th September 2018 (thanks to @Tyler):

Another possible approach is to use Array.fill() to apply the map function.

E.g.:

Array.from(Array(2), _ => Array(3).fill(43));
// Result:
// [[43, 43, 43],
//  [43, 43, 43]]

Benchmark:

https://jsperf.com/multi-dimensional-array-map-vs-fill/5

笑看君怀她人 2024-09-25 07:50:40

好吧,您可以编写一个辅助函数:

function zeros(dimensions) {
    var array = [];

    for (var i = 0; i < dimensions[0]; ++i) {
        array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1)));
    }

    return array;
}

> zeros([5, 3]);
  [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Bonus:处理任意数量的维度。

Well, you could write a helper function:

function zeros(dimensions) {
    var array = [];

    for (var i = 0; i < dimensions[0]; ++i) {
        array.push(dimensions.length == 1 ? 0 : zeros(dimensions.slice(1)));
    }

    return array;
}

> zeros([5, 3]);
  [[0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0], [0, 0, 0]]

Bonus: handles any number of dimensions.

待天淡蓝洁白时 2024-09-25 07:50:40

您可以使用以下函数创建二维零数组

const zeros = (m, n) => [...Array(m)].map(e => Array(n).fill(0));

console.log(zeros(3, 4));

// [ [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ] ]

You can use the following function to create a 2D array of zeros:

const zeros = (m, n) => [...Array(m)].map(e => Array(n).fill(0));

console.log(zeros(3, 4));

// [ [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ],
//   [ 0, 0, 0, 0 ] ]

属性 2024-09-25 07:50:40
function zero2D(rows, cols) {
  var array = [], row = [];
  while (cols--) row.push(0);
  while (rows--) array.push(row.slice());
  return array;
}
function zero2D(rows, cols) {
  var array = [], row = [];
  while (cols--) row.push(0);
  while (rows--) array.push(row.slice());
  return array;
}
像极了他 2024-09-25 07:50:40

对于初学者来说,这是一种简洁、易于理解的方法:

function twoDarrMaker(row, col) {
  const twoDarr = [];

  for (let i = 0; i < row; i++) {
    let subarray = [];

    for (let j = 0; j < col; j++) {
      subarray.push(0);
    }

    twoDarr.push(subarray);
  }

  return twoDarr;
}

twoDarrMaker(3, 2);
// [
//   [ 0, 0 ],
//   [ 0, 0 ],
//   [ 0, 0 ]
// ]

编辑:这是我的代码的解释。您创建一个数组 twoDArr 来保存二维数组或数组的数组。您使用外部 for 循环来创建子数组。然后使用内部 for 循环向子数组添加零。然后将子数组添加到外部数组 twoDarr 中。然后,重复该过程,无论外部 for 循环指定多少次。当外部 for 循环完成时,返回二维数组。

基本上,外部 for 循环创建行(子数组),而内部 for 循环创建列(子数组中的元素)。外部 for 循环告诉您通过重复块中的代码 x 次来创建 x 行(子数组),内部 for 循环告诉您创建 y 列(元素),方法是重复块中的代码 y 次。

A no-frills, easy-to-understand method for beginners:

function twoDarrMaker(row, col) {
  const twoDarr = [];

  for (let i = 0; i < row; i++) {
    let subarray = [];

    for (let j = 0; j < col; j++) {
      subarray.push(0);
    }

    twoDarr.push(subarray);
  }

  return twoDarr;
}

twoDarrMaker(3, 2);
// [
//   [ 0, 0 ],
//   [ 0, 0 ],
//   [ 0, 0 ]
// ]

Edit: Here's an explanation of my code. You create an array, twoDArr, to hold the 2d array, or array of arrays. You use the outer for loop to create subarrays. Then you use the inner for loop to add zeros to the subarray. Then you add the subarray to the outer array, twoDarr. Then you repeat the process however many times the outer for loop specifies. When the outer for loop is finished, you return the 2d array.

Basically, the outer for loop creates the rows (subarrays), while the inner for loop creates the columns (elements in the subarrays). The outer for loop tells you to create x rows (subarrays) by repeating the code in the block x times, and the inner for loop tells you to create y columns (elements) by repeating the code in the block y times.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文