When trying to modify the current item while iterating over an array the modification fails. Below is the sample code.
var s_arr = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}];
var arr = [];
for(var i in s_arr) {
if(s_arr[i].a == 5) {
s_arr[i].b = 0;
console.log('First modification: ' +JSON.stringify(s_arr[i]));
arr.push(s_arr[i]);
s_arr[i].b = 9;
console.log('Second modification: ' +JSON.stringify(s_arr[i]));
arr.push(s_arr[i]);
}
}
console.log('Final: ' +JSON.stringify(arr));
After running the above script node test.js
, below is the result.
First modification: {"a":5,"b":0}
Second modification: {"a":5,"b":9}
Final: [{"a":5,"b":9},{"a":5,"b":9}]
Expected result is as below.
First modification: {"a":5,"b":0}
Second modification: {"a":5,"b":9}
Final: [{"a":5,"b":0},{"a":5,"b":9}]
However when adding new object while iteration & assigning each values of current item (object) extensively works.
var s_arr = [{a: 1, b: 2}, {a: 3, b: 4}, {a: 5, b: 6}];
var arr = [];
for(var i in s_arr) {
if(s_arr[i].a == 5) {
s_arr[i].b = 9;
console.log('Second modification: ' +JSON.stringify(s_arr[i]));
arr.push(s_arr[i]);
var a = {};
a.a = s_arr[i].a;
a.b = 0;
arr.push(a);
var b = {};
b.a = s_arr[i].a;
b.b = 9;
arr.push(b);
}
}
console.log('Final: ' +JSON.stringify(arr));
Below is the result of modified script.
Final: [{"a":5,"b":0},{"a":5,"b":9}]
Why is the first script when ran shows modification of object right but the final array shows which consists of modified objects is not as expected?
Objects always passed by reference in JS.
arr.push(s_arr[i]);
does not create copy of object, it just save reference to it in the arr
array;
So any changes inside object you will see in the array too.
You should explicit clone your object to prevent changes.
For example you can use serialize-deserialize
pair:
arr.push(JSON.parse(JSON.stringify(s_arr[i])));
Your
var a = {};
a.a = s_arr[i].a;
a.b = 0;
arr.push(a);
will work too, because you create new object instance here and use only scalar properties to fill it.
この記事はインターネットから収集されたものであり、転載の際にはソースを示してください。
侵害の場合は、連絡してください[email protected]
コメントを追加