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
144 views
in Technique[技术] by (71.8m points)

javascript - Split a string straight into variables

I’d like to know if standard JS provides a way of splitting a string straight into a set of variables during their initial declaration. For example in Perl I would use:

my ($a, $b, $c) = split '-', $str;

In Firefox I can write

var [a, b, c] = str.split('-');

But this syntax is not part of the ECMAScript 5th edition and as such breaks in all other browsers. What I’m trying to do is avoid having to write:

var array = str.split('-');
var a = array[0];
var b = array[1];
var c = array[2];

Because for the code that I’m writing at the moment such a method would be a real pain, I’m creating 20 variables from 7 different splits and don’t want to have to use such a verbose method.

Does anyone know of an elegant way to do this?

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

You can only do it slightly more elegantly by omitting the var keyword for each variable and separating the expressions by commas:

var array = str.split('-'),
    a = array[0], b = array[1], c = array[2];

ES6 standardises destructuring assignment, which allows you to do what Firefox has supported for quite a while now:

var [a, b, c] = str.split('-');

You can check browser support using Kangax's compatibility table.


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

1.4m articles

1.4m replys

5 comments

56.9k users

...