javascript:直接将字符串拆分为变量 [英] javascript: split string straight to variables

查看:68
本文介绍了javascript:直接将字符串拆分为变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道标准JS是否提供了一种在初始声明期间将字符串直接拆分为一组变量的方法。例如在perl中我会使用:

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;

在Firefox中我可以写

In Firefox I can write

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

但是这种语法不是ECMA标准的一部分,因此在所有其他浏览器中都会中断。我要做的是避免写:

But this syntax is not part of the ECMA standard 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];

因为我现在写的代码这样的方法真的很痛苦,我正在从7个不同的分割中创建20个变量,并且不想使用这种冗长的方法。

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?

推荐答案

您只能通过省略 var 做 >每个变量的关键字并用逗号分隔表达式:

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标准化解构分配,这使你可以在很长一段时间内完成Firefox支持的工作:

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

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

您可以使用Kangax的兼容性表

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

这篇关于javascript:直接将字符串拆分为变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆