将带逗号的字符串转换为数组

本文翻译自: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] );
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值