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

看看代码:

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

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

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


当前回答

你可以使用split

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

“0 1”.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"}"]

分了就分了,人品;

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

你可以使用javascript扩展语法将字符串转换为数组。在下面的解决方案中,我删除了逗号,然后将字符串转换为数组。

var string = "0,1"
var array = [...string.replace(',', '')]
console.log(array[0])

为什么不像这样替换,逗号和分割(")字符串,这将导致['0','1'],此外,您可以将结果包装到parseInt()将元素转换为整数类型。

it('convert string to array', function () {
  expect('0,1'.replace(',', '').split('')).toEqual(['0','1'])
});

如果字符串已经是列表格式,你可以使用JSON.parse:

var a = "['a', 'b', 'c']";
a = a.replace(/'/g, '"');
a = JSON.parse(a);