search

Home  >  Q&A  >  body text

javascript - js array map method, if the original array contains objects or arrays, the original array will also change. Why?

var list = [{'a': 1},{'a': 2}];
var newList = list.map(function(index){
    return index.a += 1;
});
console.log(newList,'newList',list,'list');
// list也改变了 list = [{'a': 2},{'a': 3}]
// 本人小白,求大神指教,勿喷,谢谢!
淡淡烟草味淡淡烟草味2816 days ago766

reply all(2)I'll reply

  • PHPz

    PHPz2017-05-19 10:44:07

    It has nothing to do with map

    js objects are reference types, characters and numbers are basic types

    Basic type value transfer is copying

    Reference type passing by value is a reference

    For example:

    var a = 1;
    var b = a;
    b++;
    console.log(a);
    

    and

    var a = [1];
    var b = a;
    b[0]++;
    console.log(a);

    reply
    0
  • 我想大声告诉你

    我想大声告诉你2017-05-19 10:44:07

    You first modify a single key value of the list, and then return the key value, naturally modifying two!

    reply
    0
  • Cancelreply