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

看看代码:

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

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

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


当前回答

分了就分了,人品;

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

其他回答

使用ES6的另一个选项是使用扩展语法。

var convertedArray =[…"01234"];

var stringToConvert = "012"; var convertedArray =[…stringToConvert]; console.log (convertedArray);

Var I = "[{a:1,b:2}]", j = i.replace (/ ([a-zA-Z0-9] + ?): / g,“$ 1”:).replace (/ / g,””), k = JSON.parse(j); console.log (k)

// =>声明正则表达式

[a-zA-Z0-9] =>匹配所有a-z, a-z, 0-9

(): =>组所有匹配的元素

$1 =>替换字符串指正则表达式中的第一个匹配组。

G =>全局标志

转换所有类型的字符串

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"}"]

如何转换逗号分隔字符串成一个数组在JavaScript?

var string = 'hello, world, test, test2, rummy, words';
var arr = string.split(', '); // split string on comma space
console.log( arr );
 
//Output
["hello", "world", "test", "test2", "rummy", "words"]

在javascript中使用以下方式转换字符串到数组的更多示例:

Split() -没有分隔符: Split() -空字符串分隔符: Split() -开始/结束的分隔符: 正则表达式分隔符: 捕捉括号: 带有Limit参数的Split() 看看这个链接 = = > https://www.tutsmake.com/javascript-convert-string-to-array-javascript/

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

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