Car*_*ers 126 javascript arrays
这是一个简单的问题,我以前做过.我只是不记得它是怎么称呼的.
在python我可以这样做:
arr = ['one', 'two']
one, two = arr
Run Code Online (Sandbox Code Playgroud)
我怎么用JavaScript做到这一点?
Mat*_*ens 153
这是目前唯一的跨浏览器兼容的解决方案AFAIK:
var one = arr[0],
two = arr[1];
Run Code Online (Sandbox Code Playgroud)
ES6将允许解构分配:
let [x, y] = ['foo', 'bar'];
console.log(x); // 'foo'
console.log(y); // 'bar'
Run Code Online (Sandbox Code Playgroud)
或者,坚持你的初始例子:
var arr = ['one', 'two'];
var [one, two] = arr;
Run Code Online (Sandbox Code Playgroud)
您还可以创建默认值:
const [one = 'one', two = 'two', three = 'three'] = [1, 2];
console.log(one); // 1
console.log(two); // 2
console.log(three); // 'three'
Run Code Online (Sandbox Code Playgroud)
And*_*y E 16
这是解构任务.您可以使用以下语法在某些浏览器中执行此操作:
[one, two] = arr;
Run Code Online (Sandbox Code Playgroud)
一些最新的浏览器和转发器(如Babel和Traceur)支持它.这是ECMAScript 4引入的一个功能,后来成为ECMAScript Harmony,最终成为ES 2015.
Chr*_* K. 16
问题相当陈旧,但我想发布这个替代(2016)解决方案:也可以使用扩展运营商"......".
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_operator
let xAndY = [42, 1337];
let f = function(x, y) { return x + y; };
f(...xAndY);
Run Code Online (Sandbox Code Playgroud)
如果希望将数组项作为函数参数传递,则可以使用数组的apply函数.
实施认真的想法.
http://jsfiddle.net/RichAyotte/6D2wP/
(function(a, b, c, d) {
console.log(a, b, c, d);
}.apply(this, ['a', 'b', 'c', 'd']));
Run Code Online (Sandbox Code Playgroud)