Javascript/Jquery 将字符串转换为数组
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11776204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript/Jquery Convert string to array
提问by maaz
i have a string
我有一个字符串
var traingIds = "${triningIdArray}"; // ${triningIdArray} this value getting from server
alert(traingIds) // alerts [1,2]
var type = typeof(traingIds )
alert(type) // // alerts String
now i want to convert this to array so that i can iterate
现在我想将其转换为数组,以便我可以迭代
i tried
我试过
var trainindIdArray = traingIds.split(',');
$.each(trainindIdArray, function(index, value) {
alert(index + ': ' + value); // alerts 0:[1 , and 1:2]
});
how to resolve this?
如何解决这个问题?
采纳答案by Utkanos
Assuming, as seems to be the case, ${triningIdArray}
is a server-side placeholder that is replaced with JS array-literal syntax, just lose the quotes. So:
假设,似乎是这种情况,${triningIdArray}
是用 JS 数组文字语法替换的服务器端占位符,只需丢失引号。所以:
var traingIds = ${triningIdArray};
not
不是
var traingIds = "${triningIdArray}";
回答by Joseph
Since array literal notation is still valid JSON, you can use JSON.parse()
to convert that string into an array, and from there, use it's values.
由于数组文字表示法仍然是有效的 JSON,您可以使用JSON.parse()
该字符串将该字符串转换为数组,然后从那里使用它的值。
var test = "[1,2]";
parsedTest = JSON.parse(test); //an array [1,2]
//access like and array
console.log(parsedTest[0]); //1
console.log(parsedTest[1]); //2
回答by Clyde Lobo
Change
改变
var trainindIdArray = traingIds.split(',');
var trainindIdArray = traingIds.split(',');
to
到
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
var trainindIdArray = traingIds.replace("[","").replace("]","").split(',');
That will basically remove [
and ]
and then split the string
这将基本上去除[
和]
再分割字符串
回答by Clayton
check this out :)
看一下这个 :)
var traingIds = "[1,2]"; // ${triningIdArray} this value getting from server
alert(traingIds); // alerts [1,2]
var type = typeof(traingIds);
alert(type); // // alerts String
//remove square brackets
traingIds = traingIds.replace('[','');
traingIds = traingIds.replace(']','');
alert(traingIds); // alerts 1,2
var trainindIdArray = traingIds.split(',');
?for(i = 0; i< trainindIdArray.length; i++){
alert(trainindIdArray[i]); //outputs individual numbers in array
}?