JavaScript的字符串数组转换 [英] JavaScript string to array conversion

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

问题描述

短的问题。我怎么能一个字符串转换为JS数组?

Short question. How can I convert a string to the JS array?

看那code:

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

在这种情况下,警报将弹出一个 0.1 。当它是一个数组,它会弹出一个 0 ,并在警报(数组[1]); 是调用,它应该弹出 1

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

是否有任何机会,以这样的字符串转换成JS数组?

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

推荐答案

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

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

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


这给你的数字的Array。


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 将限制你支持的数据类型。如果你需要一个像值未定义或功能,你需要使用的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和更低或只写一个传统的循环。

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);

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

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