Unpacking array into separate variables in JavaScript

2020/11/15 21:43 · javascript ·  · 0评论

This is a simple problem, and I've done it before. I just can't remember how, or what exactly it was called.

In python I can do this:

arr = ['one', 'two']
one, two = arr

how do I do that in JavaScript?

This is currently the only cross-browser-compatible solution AFAIK:

var one = arr[0],
    two = arr[1];

ES6 will allow destructuring assignment:

let [x, y] = ['foo', 'bar'];
console.log(x); // 'foo'
console.log(y); // 'bar'

Or, to stick to your initial example:

var arr = ['one', 'two'];
var [one, two] = arr;

You could also create a default value:

const [one = 'one', two = 'two', three = 'three'] = [1, 2];
console.log(one); // 1
console.log(two); // 2
console.log(three); // 'three'

That's destructuring assignment. You can do it in some browsers with the following syntax:

[one, two] = arr;

It's supported in some of the latest browsers and transpilers like Babel and Traceur. This was a feature introduced with ECMAScript 4 which later became ECMAScript Harmony, which eventually became ES 2015.

The question is rather old but I like to post this alternative (2016) solution: One can also use the spread operator "...".


let xAndY = [42, 1337];
let f = function(x, y) { return x + y; };

You can use array's apply function if you want an array items to be passed as a function arguments.

Implementation of serious's idea.


(function(a, b, c, d) {
    console.log(a, b, c, d);   
}.apply(this, ['a', 'b', 'c', 'd']));
var one = arr[0];
var two = arr[1];

CoffeeScript has it: http://jashkenas.github.com/coffee-script/#pattern_matching

And, quoted from the top of the page:

"CoffeeScript is a little language that compiles into JavaScript. Think of it as JavaScript's less ostentatious kid brother — the same genes, roughly the same height, but a different sense of style. Apart from a handful of bonus goodies, statements in CoffeeScript correspond one-to-one with their equivalent in JavaScript, it's just another way of saying it."

文章标签: ,  
版权声明:本文为原创文章,版权归 javascript 所有,欢迎分享本文,转载请保留出处!