2014-08-27 46 views
1

有没有什么办法来存储一个javascript混合对象/数组,例如regex exec调用的输出?我注意到JSON stringify放弃了非数字数组属性。我可以做一些full object conversion magic,但是真的没有其他方法来保存结构吗?如何以json或其他格式存储JavaScript混合数组/对象并保留结构?

​​

导致

["dbBd", "bB", "d", index: 1, input: "cdbBdbsbz"] 
["dbBd", "bB", "d"] 
+0

索引和输入不是数组索引的一部分,它们是属性'console.log(result [3]); console.log(result.index);' – epascarello 2014-08-27 19:22:53

+0

你可以做类似'{“0”:“dbBd”,“1”:“bB”,“2”:“d”,“index”:1,“input “:”cdbBdbsbz“},但它不会有像'length'这样的数组属性。 – tcooc 2014-08-27 19:44:56

回答

0

指数和输入不在阵列索引的一部分,它们是属性。简单测试将显示此

console.log(result[3]);  //undefined 
console.log(result.index); //1 

如果手动编码的结果,它会像

var result = ["dbBd", "bB", "d"]; 
result.index = 1; 
result.input = "cdbBdbsbz"; 
console.log(result); 
console.log(result.toString()); 

如果你想获得的所有值,你将不得不在循环使用并建立添加属性作为对象的新数组。

var re = /d(b+)(d)/ig; 
var result = re.exec("cdbBdbsbz"); 
var updatedResult = []; //An empty array we will push our findings into 
for (propName in result) { //loop through the array which gives use the indexes and the properties 
    if (!result.hasOwnProperty(propName)) { 
     continue; 
    } 
    var val = result[propName]; 
    if(isNaN(propName)){ //check to see if it is a number [sketchy check, but works here] 
     var obj = {}; //create a new object and set the name/value 
     obj[propName] = val; 
     val = obj; 
    } 
    updatedResult.push(val); //push the number/object to the array 
} 
console.log(JSON.stringify(updatedResult)); //TADA You get what you expect 
相关问题