Javascript 将字符串直接拆分为变量
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3522406/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Split a string straight to into variables
提问by nb5
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:
我想知道标准 JS 是否提供了一种在初始声明期间将字符串直接拆分为一组变量的方法。例如在 Perl 中,我会使用:
my ($a, $b, $c) = split '-', $str;
In Firefox I can write
在 Firefox 中我可以写
var [a, b, c] = str.split('-');
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:
但是这种语法不是 ECMA 标准的一部分,因此在所有其他浏览器中都会中断。我想要做的是避免不得不写:
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.
因为对于我目前正在编写的代码来说,这样的方法真的很痛苦,我正在从 7 个不同的拆分中创建 20 个变量,并且不想使用这种冗长的方法。
Does anyone know of an elegant way to do this?
有谁知道一种优雅的方式来做到这一点?
回答by Andy E
You can only do it slightlymore elegantly by omitting the varkeyword for each variable and separating the expressions by commas:
您只能通过省略每个变量的var关键字并用逗号分隔表达式来稍微优雅地完成它:
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:
ES6 标准化了解构赋值,它允许你做 Firefox 已经支持了很长时间的事情:
var [a, b, c] = str.split('-');
You can check browser support using Kangax's compatibility table.
您可以使用 Kangax 的兼容性表来检查浏览器支持情况。
回答by viam0Zah
var str = '123',
array = str.split('');
(function(a, b, c) {
a; // 1
b; // 2
c; // 3
}).apply(null, array)
回答by abhisekp
Split a string into two part variables for a 3 or more word sentence.
将字符串拆分为 3 个或更多单词的句子的两个部分变量。
> var [firstName, lastName] = 'Ravindra Kumar Padhi'.split(/(\w+)$/)
> console.log({firstName: firstName.trim(), lastName: lastName.trim()})
{ firstName: 'Ravindra Kumar', lastName: 'Padhi' }
回答by Gary
You could create a function that will loop through the Array that's created by the str.split method and auto generate variables this way:
您可以创建一个函数来循环遍历由 str.split 方法创建的 Array 并以这种方式自动生成变量:
function autoGenerateVarFromArray(srcArray, varNamePrefix)
{
var i = 0
while(i < srcArray.length)
{
this[varNamePrefix +'_' + i] = srcArray[i];
i++;
}
}
Here's an example of how to use this:
以下是如何使用它的示例:
var someString = "Mary had a little Lamb";
autoGenerateVarFromArray(someString.split(' '), 'temp');
alert(this.temp_3); // little

