将带逗号的字符串转换为数组 [英] Convert string with commas to array

查看:391
本文介绍了将带逗号的字符串转换为数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何将字符串转换为JavaScript数组?

How can I convert a string to a JavaScript array?

查看代码:

var string = "0,1";
var array = [string];
alert(array[0]);

在这种情况下, alert 会弹出 - 上 0,1 。当它是一个数组时,它会弹出 0 ,当 alert(array [1]); 被调用,它应该弹出 1

In this case, alert would pop-up a 0,1. When it would be an array, it would pop-up a 0, and when alert(array[1]); is called, it should pop-up the 1.

有没有机会将这样的字符串转换为JavaScript数组?

Is there any chance to convert such string into a JavaScript array?

推荐答案

对于像这样的简单数组成员,可以使用 JSON.parse

For simple array members like that, you can use JSON.parse.

var array = JSON.parse("[" + string + "]");






这会给你一个数字数组。


This gives you an Array of numbers.

[0, 1]

如果你使用 .split(),你最终会得到一个字符串数组。

If you use .split(), you'll end up with an Array of strings.

["0", "1"]






请注意, JSON.parse 将限制您使用支持的数据类型。如果您需要 undefined 或函数等值,则需要使用 eval()或JavaScript解析器。


Just be aware that JSON.parse will limit you to the supported data types. If you need values like undefined or functions, you'd need to use eval(), or a JavaScript parser.

如果你想使用 .split(),但是你也想要一个数字数组,你可以使用 Array.prototype.map ,虽然你需要为IE8填充它并降低或者只是写一个传统的循环。 / p>

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.

var array = string.split(",").map(Number);

这篇关于将带逗号的字符串转换为数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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