如何将以下字符串转换为javascript中的数组
var data = "[
[[1400586475733,-1],
[1400586535736,-1],
[1400586595739,-1],
[1400586655742,-1],
[1400586715745,-1]],
[[1400586475733,0],
[1400586535736,0],
[1400586595739,0],
[1400586655742,0],
[1400586715745,0]]
]";
预期产出
data[0] = [[1400586475733,-1],[1400586535736,-1],[1400586595739,-1],[1400586655742,-1],[1400586715745,-1]]; ==> of type object Array
data[0][0] = 1400586475733 ==> of type number
data[0][1] = -1 ==> of type number
答案 0 :(得分:3)
我还没有彻底尝试过,但它应该有效:
var string = "[[[1400586475733,-1],[1400586535736,-1],[1400586595739,-1],[1400586655742,-1],[1400586715745,-1]],[[1400586475733,0],[1400586535736,0],[1400586595739,0],[1400586655742,0],[1400586715745,0]]]";
var dataFromString = string.split(",");
var finalArray = [];
var arrayStartRegEx = new RegExp(/^\[/);
var arrayEndRegEx = new RegExp(/\]$/);
var currentArray = finalArray;
var arrayHistory = [];
for(var i = 0; i < dataFromString.length; i++) {
var currentString = dataFromString[i];
var closingArray = false;
while(arrayStartRegEx.test(currentString) === true) {
// Save previous array
// createArray
// add to big array
// currentArray = createdArray
// remove bracket
var arr = []
arrayHistory.push(currentArray);
currentArray.push(arr);
currentArray = arr;
currentString = currentString.slice(1,currentString.length - 1);
}
while(arrayEndRegEx.test(currentString) === true){
// remove bracket
// add element to array
// close currentArray
// currentArray = big array
currentString = currentString.slice(0,-1);
if(!closingArray) {
var string = currentString.replace(/\]/g, '');
// Use parseFloat if you know it's going to be a float
currentArray.push(parseInt(string));
closingArray = true;
}
currentArray = arrayHistory.pop();
}
if(arrayStartRegEx.test(currentString) === false && arrayEndRegEx.test(currentString) === false) {
// add element to array
currentArray.push(parseInt(currentString))
}
}
console.log(finalArray);