js创建二维数组

Author Avatar
zzz1220 10月 21, 2023
  • 在其它设备中阅读本文章
👉👉本文共189字📘 读完共需1分钟⌚

js 创建二维数组不像java那么直白

// 初始化一个3 * 3 的二维数组
int nums[][] = new int[3][3];

之前我都是这样写的

const nums = new Array(3).fill(0).map(() => new Array(3).fill(0))

今天看到一个更简洁的写法

const nums = Array.from({ length: 3 }, () => [0,0,0]);

主要是利用了Array.from这个语法
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/from

Array.from(arrayLike)
Array.from(arrayLike, mapFn)
Array.from(arrayLike, mapFn, thisArg)

主要是第一个参数,可以传入一个arrayLike对象,这里可以传{ length: 3 },比起我之前的写法,看起来更简洁和可读。

console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], (x) => x + x));
// Expected output: Array [2, 4, 6]