<script>
var arr = [{"val":0},{"val":1},{"val":2},{"val":3},{"val":4},{"val":5}];
var arrCopy = [];
for(var i=0; i < arr.length; i++){
var tmp = arr[i];
arrCopy.push(tmp);
}
for(var j=0; j < arrCopy.length; j++){
arrCopy[j].val = arrCopy[j].val+1;
}
console.log("arr:", arr); //resullt: [{"val",1},{"val",2},{"val",3},{"val",4},{"val",5},{"val",6}]
console.log("arrCopy", arrCopy);//resullt: [{"val",1},{"val",2},{"val",3},{"val",4},{"val",5},{"val",6}]
</script>
答案 0 :(得分:0)
你的语法中只有一个小错误;而不是在每个{"val",0}
地图中使用逗号,而是使用冒号:{"val":0}
。因此,请将arr
更改为
var arr = [{"val":0},{"val":1},{"val":2},{"val":3},{"val":4},{"val":5}];
通过这样做,你说的是从"val"
到冒号右边的数字的映射。
答案 1 :(得分:0)
问题是当你说
时tmp = arr[i] // it's just a reference of {"val":0} to tmp not a copy.
更好地做到这一点
var tmp = {};
tmp.val = arr[i].val;