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

看看代码:

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

在这种情况下,警报显示0,1。如果它是一个数组,它将显示0。如果调用alert(数组[1]),它应该弹出1

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


当前回答

下面是更多“自己试试”的例子。

定义和用法 split()方法用于将字符串拆分为子字符串数组,并返回新数组。

提示:如果使用空字符串(“”)作为分隔符,则字符串在每个字符之间被分割。

注意:split()方法不会改变原始字符串。

var res = str.split(",");

其他回答

转换所有类型的字符串

var array = (new Function("return [" + str+ "];")());



var string = "0,1";

var objectstring = '{Name:"Tshirt", CatGroupName:"Clothes", Gender:"male-female"}, {Name:"Dress", CatGroupName:"Clothes", Gender:"female"}, {Name:"Belt", CatGroupName:"Leather", Gender:"child"}';

var stringArray = (new Function("return [" + string+ "];")());

var objectStringArray = (new Function("return [" + objectstring+ "];")());

JSFiddle https://jsfiddle.net/7ne9L4Lj/1/

控制台结果

一些练习不支持对象字符串

- JSON.parse("[" + string + "]"); // throw error

 - string.split(",") 
// unexpected result 
   ["{Name:"Tshirt"", " CatGroupName:"Clothes"", " Gender:"male-female"}", "      {Name:"Dress"", " CatGroupName:"Clothes"", " Gender:"female"}", " {Name:"Belt"",    " CatGroupName:"Leather"", " Gender:"child"}"]

Split(",")可以将带有逗号的字符串转换为字符串数组,这是我的代码片段。

    var input ='Hybrid App, Phone-Gap, Apache Cordova, HTML5, JavaScript, BootStrap, JQuery, CSS3, Android Wear API'
    var output = input.split(",");
    console.log(output);

["混合应用"," Phone-Gap", " Apache Cordova", " HTML5", " JavaScript", " BootStrap", " JQuery", " CSS3", " Android Wear API"]

你可以使用split

参考: http://www.w3schools.com/jsref/jsref_split.asp

“0 1”.split (" ")

分了就分了,人品;

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

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

var listValues = "[{\"ComplianceTaskID\":75305,\"RequirementTypeID\":4,\"MissedRequirement\":\"Initial Photo Upload NRP\",\"TimeOverdueInMinutes\":null}]";

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

这给了你一个数字数组。

现在你的变量值是array。length=1

值输出

array[0].ComplianceTaskID
array[0].RequirementTypeID
array[0].MissedRequirement
array[0].TimeOverdueInMinutes