本文翻译自:Convert string with commas to array
How can I convert a string to a JavaScript array? 如何将字符串转换为JavaScript数组?
Look at the code: 看看代码:
var string = "0,1";
var array = [string];
alert(array[0]);
In this case, alert
would pop-up a 0,1
. 在这种情况下, alert
会弹出一个0,1
。 When it would be an array, it would pop-up a 0
, and when alert(array[1]);
当它是一个数组时,它会弹出一个0
,当alert(array[1]);
is called, it should pop-up the 1
. 被叫,它应该弹出1
。
Is there any chance to convert such string into a JavaScript array? 有没有机会将这样的字符串转换为JavaScript数组?
#1楼
参考:https://stackoom.com/question/tgl4/将带逗号的字符串转换为数组
#2楼
Split it on the ,
character; 将它拆分为,
字符;
var string = "0,1";
var array = string.split(",");
alert(array[0]);
#3楼
For simple array members like that, you can use JSON.parse
. 对于像这样的简单数组成员,您可以使用JSON.parse
。
var array = JSON.parse("[" + string + "]");
This gives you an Array of numbers. 这会给你一个数字数组。
[0, 1]
If you use .split()
, you'll end up with an Array of strings. 如果你使用.split()
,你最终会得到一个字符串数组。
["0", "1"]
Just be aware that JSON.parse
will limit you to the supported data types. 请注意, JSON.parse
会限制您使用支持的数据类型。 If you need values like undefined
or functions, you'd need to use eval()
, or a JavaScript parser. 如果您需要undefined
或函数等值,则需要使用eval()
或JavaScript解析器。
If you want to use .split()
, but you also want an Array of Numbers, you could use Array.prototype.map
, though you'd need to shim it for IE8 and lower or just write a traditional loop. 如果你想使用.split()
,但你也想要一个数字数组,你可以使用Array.prototype.map
,虽然你需要为IE8填充它并降低或者只是写一个传统的循环。
var array = string.split(",").map(Number);
#4楼
You can use split
你可以使用split
Reference: http://www.w3schools.com/jsref/jsref_split.asp 参考: http : //www.w3schools.com/jsref/jsref_split.asp
"0,1".split(',')
#5楼
For simple array members like that, you can use JSON.parse. 对于像这样的简单数组成员,您可以使用JSON.parse。
var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";
var array = JSON.parse("[" + listValues + "]");
This gives you an Array of numbers. 这会给你一个数字数组。
now you variable value is like array.length=1 现在你的变量值就像array.length = 1
Value output 价值输出
array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes
#6楼
use the built-in map function with an anonymous function, like so: 使用带有匿名函数的内置map函数,如下所示:
string.split(',').map(function(n) {return Number(n);});
[edit] here's how you would use it [编辑]这是你如何使用它
var string = "0,1";
var array = string.split(',').map(function(n) {
return Number(n);
});
alert( array[0] );