【问题标题】:What can I use as placeholders in es6 array destructuring?我可以在 es6 数组解构中使用什么作为占位符?
【发布时间】:2016-05-07 07:58:24
【问题描述】:

我不喜欢这里的, ,

let colors = [ "red", "green", "blue" ];
let [ , , thirdColor] = colors;

我可以使用一些占位符吗?我宁愿不引入未使用的变量,我只是想让代码看起来更清晰。现在我唯一能想到的就是 cmets:

let [/*first*/, /*second*/, thirdColor] = colors;

有更好的想法吗?

【问题讨论】:

    标签: javascript ecmascript-6 syntactic-sugar


    【解决方案1】:

    JS 中没有占位符的概念。通常_ 用于此目的,但实际上您不能在一个声明中多次使用它:

    let [_, secondColor] = colors; // OK
    let [_, _, thirdColor] = colors; // error
    

    另外,_ 实际上可能会在您的代码中使用,因此您必须想出另一个名称,等等。

    最简单的方法可能是直接访问第三个元素:

    let thirdColor = colors[2];
    let {2: thirdColor, 10: eleventhColor} = colors;
    

    【讨论】:

    • 应该[_, _, thirdColor] 实际产生错误吗? Firefox 的实现允许它;我还没有深入研究规范,看看这是否是错误的。
    • [_, _, thirdcolor] = ....let [_, _, thirdColor] = ... 是不同的。第一个很好,因为它只是一个变量赋值,但第二个是变量声明,let 不允许重新声明。在这种情况下,Firefox 也会抛出一个错误:(function() { "use strict"; let [_, _,] = [1,2]; }()) 给出TypeError: redeclaration of let _
    • 哦,我正在测试顶级范围,这显然允许 let 重新声明。 (确实,当您的变量具有顶级可见性时,我可以理解 let 并不是特别有意义,所以我可以看到为什么那里可能会有不同的行为。)当我将它移动到函数或块中时,它确实引发错误。
    猜你喜欢
    • 2013-08-28
    • 2020-10-20
    • 2019-02-06
    • 2021-12-11
    • 2015-10-03
    • 1970-01-01
    • 2017-06-02
    • 1970-01-01
    • 2016-06-11
    相关资源
    最近更新 更多