Array modification while iteration

Ayaz Pasha

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?

vp_arth

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]

編集
0

コメントを追加

0

関連記事

TOP 一覧

  1. 1

    モーダルダイアログを自動的に閉じる-サーバーコードが完了したら、Googleスプレッドシートのダイアログを閉じます

  2. 2

    セレンのモデルダイアログからテキストを抽出するにはどうすればよいですか?

  3. 3

    CSSのみを使用して三角形のアニメーションを作成する方法

  4. 4

    ドロップダウンリストで選択したアイテムのQComboBoxスタイル

  5. 5

    ZScalerと証明書の問題により、Dockerを使用できません

  6. 6

    PyCharmリモートインタープリターはプロジェクトタブにサイトパッケージのコンテンツを表示しません

  7. 7

    Windows 10でのUSB入力デバイスの挿入/取り外しの検出

  8. 8

    Excel - count multiple words per cell in a range of cells

  9. 9

    PictureBoxで画像のブレンドを無効にする

  10. 10

    Windows 10 Pro 1709を1803、1809、または1903に更新しますか?

  11. 11

    スタート画面にシャットダウンタイルを追加するにはどうすればよいですか?

  12. 12

    Python / SciPyのピーク検出アルゴリズム

  13. 13

    Luaの文字列から特定の特殊文字を削除するにはどうすればよいですか?

  14. 14

    Pythonを使用して、リストからデータを読み取り、特定の値をElasticsearchにインデックス付けするにはどうすればよいですか?

  15. 15

    LinuxでPySide2(Qt for Python)をインストールするQt Designerはどこにありますか?

  16. 16

    goormIDEは、ターミナルがロードするデフォルトプロジェクトを変更します

  17. 17

    QGISとPostGIS(マップポイント(米国の地図上にraduisを使用した緯度と経度)

  18. 18

    MLでのデータ前処理の背後にある直感

  19. 19

    ターミナルから「入力ソースの変更」ショートカットを設定する

  20. 20

    パンダは異なる名前の列に追加します

  21. 21

    同じクラスの異なるバージョンを使用したクラスローディング:java.lang.LinkageError:名前の重複クラス定義を試行しました

ホットタグ

アーカイブ