javascript return reference to array item

后端 未结 7 2180
逝去的感伤
逝去的感伤 2020-12-28 16:11

I have a array like this:

users = [{id:1, name:\'name1\'},{id:2, name:\'name2\'}]

How could I get a reference to the item {id:2, name:\'nam

相关标签:
7条回答
  • 2020-12-28 16:49

    Here is the code which will better explain the scenario. Run the script and will understand.

    var arr = [
    	{"name": "James", "age": 34},
    	{"name": "Peter", "age": 67}
    ];
    
    var p1 = arr.filter(function(p){return p.name=="James"});
    p1[0] = {"name": "James", "age": 50};
    console.log(JSON.stringify(arr)); // Won't work
    
    var p2 = arr.filter(function(p){return p.name=="James"});
    p2[0].age = 50;
    console.log(JSON.stringify(arr)); // Voila... this works

    0 讨论(0)
提交回复
热议问题