[英]JS: convert string to array
I have this string 我有这串
foo = "[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]";
How can I convert this into a JavaScript array (likely without splitting the string, because there are over 16,000 values in the array and I want to save time)? 如何将其转换为JavaScript数组(可能不拆分字符串,因为数组中有16,000个以上的值,并且我想节省时间)?
Did you mean to merge all the sub-arrays into one? 您是否要将所有子阵列合并为一个? If yes, you could try with the following snippet: 如果是,则可以尝试使用以下代码段:
var foo = '[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]'; var list = JSON.parse(foo); var combined = new Array(); for (var counter = 0; counter < list.length; counter++) { for(var index = 0; index < list[counter].length; index++) { combined.push(list[counter][index]); } } console.log(combined);
You can use JSON.parse
to convert the string into array, then use .concat
method to merge the arrays into one. 您可以使用JSON.parse
将字符串转换为数组,然后使用.concat
方法将数组合并为一个。
DEMO 演示
var foo = "[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]"; var output = JSON.parse(foo); var merged = [].concat.apply([], output); console.log(merged);
Make use of reduce function available on array 利用数组上可用的reduce函数
var foo = "[[0,0,0,0],[1,24,3,3],[2,24,0,3],[3,24,0,3],[4,24,19,3]]"; var nested_array = JSON.parse(foo); var output = nested_array.reduce(function(prev, curr) { return prev.concat(curr); }); console.log(output)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.