zer*_*298 5 javascript arrays destructuring
我正在自我回答这个问题,因为我没有遇到讨论在搜索时忽略解构数组元素的问题或答案。
有没有办法在解构时忽略数组的元素?我能想到的最接近的事情是在 Go 中如何使用_符号来删除参数。
我正在使用 ESLint,我希望能够避免未使用的变量警告,而不必明确关闭警告。我也不喜欢范围泄漏,即使它相当小。
例如:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// I don't actually want 'a' to be available in the scope
arr.forEach(([a, b]) => console.log(`a: ${a} | b: ${b}`));
// _ is still defined and equates to 'a' above
arr.forEach(([_, b]) => console.log(`'a': ${_} | b: ${b}`));Run Code Online (Sandbox Code Playgroud)
您可以通过简单地不为要分配的值提供变量而只是像使用逗号一样放置逗号来忽略元素。请参阅MDN:解构赋值#忽略一些返回值。
例如:
const arr = [
["foo", "bar"],
["fizz", "buzz"],
["hello", "world"]
];
// Just use ','
arr.forEach(([, b]) => {
// No variable is populated with the first element
console.log(typeof(a));
console.log(typeof(b));
console.log(`b: ${b}`);
});Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1269 次 |
| 最近记录: |