如何忽略数组解构的某些返回值?
How can I ignore certain returned values from array destructuring?
当我只对索引 0 以外的数组值感兴趣时,是否可以在数组解构时避免声明无用变量?
在下文中,我想避免声明 a
,我只对索引 1 及以后的索引感兴趣。
// How can I avoid declaring "a"?
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest);
Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 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);
忽略一些 returned 值
您可以使用“,”忽略您不感兴趣的 return 值:
const [, b, ...rest] = [1, 2, 3, 4, 5];
console.log(b);
console.log(rest);
当我只对索引 0 以外的数组值感兴趣时,是否可以在数组解构时避免声明无用变量?
在下文中,我想避免声明 a
,我只对索引 1 及以后的索引感兴趣。
// How can I avoid declaring "a"?
const [a, b, ...rest] = [1, 2, 3, 4, 5];
console.log(a, b, rest);
Can I avoid declaring a useless variable when array destructuring when I am only interested in array values beyond index 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);
忽略一些 returned 值
您可以使用“,”忽略您不感兴趣的 return 值:
const [, b, ...rest] = [1, 2, 3, 4, 5];
console.log(b);
console.log(rest);