将多维数组函数重构为ES6

时间:2017-09-19 17:49:37

标签: javascript arrays function multidimensional-array ecmascript-6

目前在我的应用程序中放置了一个函数,并且想知道是否有一种更简洁的方式来编写这个用ES6而不是使用两个for循环。

目标是创建一个多维数组来跟踪坐标x&年。这样可以正常工作,但我希望能让它更整洁。

function setBoard() {
boardParts = new Array(tileCount);
for (let i = 0; i < tileCount; ++i) {
    boardParts[i] = new Array(tileCount);
    for (let j = 0; j < tileCount; ++j) {
        boardParts[i][j] = new Object();
        boardParts[i][j].x = tileCount - 1 - i;
        boardParts[i][j].y = tileCount - 1 - j;
    }
}
emptyLoc.x = boardParts[tileCount - 1][tileCount - 1].x;
emptyLoc.y = boardParts[tileCount - 1][tileCount - 1].y;
solved = false;
}

感谢任何帮助!

由于

2 个答案:

答案 0 :(得分:2)

如果您想使用ES6,可以使用Array#from生成数组:

&#13;
&#13;
const tileCount = 4;

const boardParts = Array.from({ length: tileCount }, (_, i) => 
  Array.from({ length: tileCount }, (_, j) => ({
    x: tileCount - 1 - i,
    y: tileCount - 1 - j
  }))
);

console.log(boardParts);
&#13;
&#13;
&#13;

答案 1 :(得分:1)

在ES2015 +中没有什么特别的帮助(除了Array.from as Ori Drori points out,你可能会或可能不想要),但你可以做几件事改进它也可以在ES5中找到,见评论:

function setBoard() {
    boardParts = []; // No need to create with initial `length`, generic arrays
                     // aren't really arrays, no pre-allocation necessary
    for (let i = 0; i < tileCount; ++i) {
        boardParts[i] = []; // See above
        for (let j = 0; j < tileCount; ++j) {
            boardParts[i][j] = {           // Object initializer rather than
                x: tileCount - 1 - i,      // `new Object` and then prop
                y: tileCount - 1 - j       // assignment
            };
        }
    }
    emptyLoc.x = boardParts[tileCount - 1][tileCount - 1].x;
    emptyLoc.y = boardParts[tileCount - 1][tileCount - 1].y;
    solved = false;
}

与上述内容分开:所提供的功能希望在包含的上下文中找到boardPartstileCountemptyLocsolved。通常情况下,除非他们反对某种类型的初始化器,否则完全通过副作用的功能并不理想......