简体   繁体   English

在ES6中创建多维数组

[英]Creating multidimensional arrays in ES6

What is the cleanest way of allocating a multidimentional array in javascript? 在javascript中分配多维数组的最干净方法是什么? Or is it even necessary? 还是有必要? Currently I am doing it like so 目前我正在这样做

let dp = new Array(8).fill(null).map(item =>(new Array(8).fill(null).map(item =>(new Array(8).fill(null))))); (for 8x8x8). (适用于8x8x8)。

Or can i just do let dp = new Array(); dp[1][1][1] = 7 或者我可以let dp = new Array(); dp[1][1][1] = 7 let dp = new Array(); dp[1][1][1] = 7 ? let dp = new Array(); dp[1][1][1] = 7 Wondering the best way to do stuff like this 想知道做这样的事情的最佳方法

One possibility is to create a makeArr function which recursively calls itself, to which you can pass a nested object indicating the length and values desired, something like this: 一种可能性是创建一个递归调用自身的makeArr函数,您可以向其传递一个嵌套对象,该对象指示所需的长度和值,如下所示:

 const makeArr = (length, item) => Array.from( { length }, () => typeof item === 'object' ? makeArr(item.length, item.item) : item ); const arrx3x3 = makeArr(3, { length: 3, item: { length: 3, item: 0 } }); // check that every array is a separate reference: arrx3x3[0][0][0] = 1; console.log(arrx3x3); 

This will allow for relatively clean creation of arbitrary array dimensions. 这将允许相对干净地创建任意数组维。

If every nested array will have the same length, then you just need to indicate the length on the first parameter to makeArr : 如果每个嵌套数组的长度都相同,则只需在makeArr的第一个参数上指定length

 const makeArr = (length, item) => Array.from( { length }, () => typeof item === 'object' ? makeArr(length, item.item) : item ); const arrx3x3 = makeArr(3, { item: { item: 0 } }); // check that every array is a separate reference: arrx3x3[0][0][0] = 1; console.log(arrx3x3); 

If you want to fill the nested array items with non-array objects (eg where the 0 is now, in the nested item : 0 ), you'll have to change the typeof item === 'object' test to something more precise. 如果要用非数组对象填充嵌套数组项目(例如,现在嵌套的item : 0现在为0 ,则在嵌套item : 0 ),则必须将typeof item === 'object'测试更改为更精确的值。

I would use Array.from() and pass an array of size, and a value ( val ) for the last arrays. 我将使用Array.from()并传递一个大小为数组的数组,以及最后一个数组的值( val )。 Use array destructuring, and rest to get the current array length, and array of the next nested arrays. 使用数组解构,然后休息以获取current数组长度以及next嵌套数组的数组。 If the next array is not empty, use the result of calling the function again. 如果next数组不为空,则使用再次调用该函数的结果。 If not, return the val . 如果不是,则返回val

 const generateMulti = ([current, ...next], val) => Array.from({ length: current }, () => next.length ? generateMulti(next, val) : val ) const result = generateMulti([3, 2, 2], null) console.log(JSON.stringify(result)) 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM