【问题标题】:How can I ignore certain returned values from array destructuring?如何忽略数组解构的某些返回值?
【发布时间】:2017-10-16 16:40:11
【问题描述】:

当我只对索引 0 以外的数组值感兴趣时,我可以避免在数组解构时声明一个无用的变量吗?

在下文中,我想避免声明 a,我只对索引 1 及以后感兴趣。

// How can I avoid declaring "a"?
const [a, b, ...rest] = [1, 2, 3, 4, 5];

console.log(a, b, rest);

【问题讨论】:

标签: javascript arrays destructuring


【解决方案1】:

当我只对索引 0 以外的数组值感兴趣时,我可以避免在数组解构时声明无用的变量吗?

是的,如果您将分配的第一个索引留空,则不会分配任何内容。这种行为是explained here

// The first value in array will not be assigned
const [, b, ...rest] = [1, 2, 3, 4, 5];

console.log(b, rest);

你可以在任何你喜欢的地方使用任意数量的逗号,除了在休息元素之后:

const [, , three] = [1, 2, 3, 4, 5];
console.log(three);

const [, two, , four] = [1, 2, 3, 4, 5];
console.log(two, four);

以下产生错误:

const [, ...rest,] = [1, 2, 3, 4, 5];
console.log(rest);

【讨论】:

  • 是否可以忽略前面的所有项目而只保留最后固定的一堆?类似const [..., fourth_to_last, , penultimate, last] = my_list;
  • @BallpointBen,这是一个有趣的问题。不幸的是,其余元素必须是最后一个元素。获取最后一项的一种简单方法是反转数组和变量:const [last, penultimate, , fourth_to_last] = my_list.reverse();
【解决方案2】:

忽略一些返回值

您可以使用 ',' 忽略您不感兴趣的返回值:

const [, b, ...rest] = [1, 2, 3, 4, 5];

console.log(b);
console.log(rest);

【讨论】:

    猜你喜欢
    • 2010-10-19
    • 2017-06-16
    • 1970-01-01
    • 1970-01-01
    • 2014-12-02
    • 2012-07-28
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多