从索引为 1 或更高的返回数组中分配元素
Assigning elements from returned array where index is 1 or higher
给定一个函数,return一个包含 (n) 个元素的数组。
我想分配这些 return 个值,但不是第一个。
// match returns ["abc123","abc","123"] here
[ foo, bar ] = "abc123".match(/([a-z]*)([0-9]*)/);
现在我有
foo = "abc123"
bar = "abc"
但我的意图是
foo = "abc"
bar = "123"
在其他语言中,您可以执行类似
的操作
//pseudocode
[_,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);
要存档,但在 JS 中是如何完成的?
当然可以
[garbage,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);
garbage = undefined;
..但是..呃..
您可以使用Array.prototype.slice()
提取数组的子序列。
[foo, bar] = "abc123".match(/([a-z]*)([0-9]*)/).slice(1);
请注意,这种多变量赋值是 EcmaScript 6 的一项功能,因此它不适用于旧版浏览器。语法要求将它们括在数组括号中(您要从值数组中分配变量数组)。
我假设您使用的是 ES6(ECMAScript 2015,JavaScript 的最新版本)。如果是这样,你的伪代码真的很接近,你甚至不需要在第一个位置使用变量名,你可以完全不使用它:
[ , foo, bar] = "abc123".match(/([a-z]*)([0-9]*)/);
注意前导逗号。将索引 1 的值存储在 foo
中,将索引 2 的值存储在 bar
.
中
Live Example 在 Babel 的 REPL
您可以在左侧序列中的任何一点执行此操作。例如,假设您希望 foo
是 0 的值,bar
是 2 的值:
// Different from what the question asks, an example
// of grabbing index 0 and index 2
[foo, , bar] = "abc123".match(/([a-z]*)([0-9]*)/);
因为我们没有在左边第二个位置放置任何东西,所以在解构赋值过程中它被跳过了。
给定一个函数,return一个包含 (n) 个元素的数组。 我想分配这些 return 个值,但不是第一个。
// match returns ["abc123","abc","123"] here
[ foo, bar ] = "abc123".match(/([a-z]*)([0-9]*)/);
现在我有
foo = "abc123"
bar = "abc"
但我的意图是
foo = "abc"
bar = "123"
在其他语言中,您可以执行类似
的操作//pseudocode
[_,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);
要存档,但在 JS 中是如何完成的?
当然可以
[garbage,foo,bar] = "abc123".match(/([a-z]*)([0-9]*)/);
garbage = undefined;
..但是..呃..
您可以使用Array.prototype.slice()
提取数组的子序列。
[foo, bar] = "abc123".match(/([a-z]*)([0-9]*)/).slice(1);
请注意,这种多变量赋值是 EcmaScript 6 的一项功能,因此它不适用于旧版浏览器。语法要求将它们括在数组括号中(您要从值数组中分配变量数组)。
我假设您使用的是 ES6(ECMAScript 2015,JavaScript 的最新版本)。如果是这样,你的伪代码真的很接近,你甚至不需要在第一个位置使用变量名,你可以完全不使用它:
[ , foo, bar] = "abc123".match(/([a-z]*)([0-9]*)/);
注意前导逗号。将索引 1 的值存储在 foo
中,将索引 2 的值存储在 bar
.
Live Example 在 Babel 的 REPL
您可以在左侧序列中的任何一点执行此操作。例如,假设您希望 foo
是 0 的值,bar
是 2 的值:
// Different from what the question asks, an example
// of grabbing index 0 and index 2
[foo, , bar] = "abc123".match(/([a-z]*)([0-9]*)/);
因为我们没有在左边第二个位置放置任何东西,所以在解构赋值过程中它被跳过了。