Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Is it a standard way to assign to multiple variables from an array in JavaScript? In Firefox and Opera, you can do:

var [key, value] = "key:value".split(":");
alert(key + "=" + value); // will alert "key = value";

But it doesn't work in IE8 or Google Chrome.

Does anyone know a nice way to do this in other browsers without a tmp variable?

var tmp = "key:value".split(":");
var key=tmp[0], value=tmp[1];

Is this something that will come in an upcoming JavaScript version, or just custom implementation in FF and Opera?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
159 views
Welcome To Ask or Share your Answers For Others

1 Answer

Destructuring assignment was standardized in ECMAScript 2015 (a.k.a. ES6). But not all browsers have implemented destructuring yet (as of March 2016), and even when they do it will take a while before users update to a browser with support. See examples in the spec for all the awesome things you can do. Here are some:

// Assign from array elements
var [key, value] = "key:value".split(":");
// key => 'key'
// value => 'value'

// Assign from object properties
var {name: a, age: b} = {name: 'Peter', age: 5};
// a => 'Peter'
// b => 5

// Swap
[a, b] = [b, a]
// a => 5
// b => 'Peter'

Because this feature breaks backwards compatibility, you'll need to transpile the code to make it work in all browsers. Many of the existing transpilers support destructuring. Babel is a very popular transpiler. See Kangax′s table of browser and transpiler ES6-support.

More info:

Compatibility table for ES6 browser support

Exploring ES6 - Destructuring chapter


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share

548k questions

547k answers

4 comments

86.3k users

...