将字符串直接分割成变量 [英] Split a string straight to into variables

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

问题描述

我想知道标准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.

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

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