Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
177 views
in Technique[技术] by (71.8m points)

javascript - Possible to assign to multiple variables from an array?

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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...