【问题标题】:Refactor multidimensional array function to ES6将多维数组函数重构为 ES6
【发布时间】:2018-02-28 14:49:03
【问题描述】:

目前在我的应用程序中组合了一个函数,想知道是否有一种更简洁的方法来使用 ES6 编写此函数,而不是使用两个 for 循环。

目的是创建一个多维数组来跟踪坐标 x 和 y。这工作正常,但我希望让它更整洁。

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;
}

感谢任何帮助!

谢谢

【问题讨论】:

  • 即使在 ES5 中也有对象字面量 :-)
  • 另外,emptyLoc.x = emptyLoc.y = 0; - 那些总是一样的?

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


【解决方案1】:

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

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);

【讨论】:

  • 好吧,很公平,在 ES2015 中有 与此相关的东西。我不会说这一定是一种改进,但 OP 确实特别问... :-)
  • @T.J.Crowder - Array#from 是最接近 Python 列表解析的 JS,可惜 JS 尚不支持 array comprehensions
【解决方案2】:

在 ES2015+ 中没有什么特别的帮助(嗯,除了 Array.from as Ori Drori points out,你可能想要也可能不想要),但是你可以做一些事情来改进它,这些事情在 ES5 中也可用,见 cmets:

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。通常,拥有纯粹通过副作用工作的函数并不理想,除非它们是某种类型的对象初始化器......

【讨论】:

    猜你喜欢
    • 2016-11-10
    • 2017-10-12
    • 1970-01-01
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2017-05-06
    • 1970-01-01
    相关资源
    最近更新 更多