Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
341 views
in Technique[技术] by (71.8m points)

javascript - 将带逗号的字符串转换为数组(Convert string with commas to array)

How can I convert a string to a JavaScript array?

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

Look at the code:

(看看代码:)

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

In this case, alert would pop-up a 0,1 .

(在这种情况下, alert会弹出一个0,1 。)

When it would be an array, it would pop-up a 0 , and when alert(array[1]);

(当它是一个数组时,它会弹出一个0 ,当alert(array[1]);)

is called, it should pop-up the 1 .

(被叫,它应该弹出1 。)

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

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

  ask by Scott translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

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

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

This gives you an Array of numbers.

(这会给你一个数字数组。)

[0, 1]

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

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

["0", "1"]

Just be aware that JSON.parse will limit you to the supported data types.

(请注意, JSON.parse会限制您使用支持的数据类型。)

If you need values like undefined or functions, you'd need to use eval() , or a JavaScript parser.

(如果您需要undefined或函数等值,则需要使用eval()或JavaScript解析器。)


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.

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

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...