简体   繁体   English

slice()到对象数组没有返回引用?

[英]slice() to the array of object didn't return a reference?

Please help me, I am really confused with the slice() of javascript. 请帮助我,我真的对slice()感到困惑。 I have read the documentation of Array.prototype.slice() . 我已经阅读了Array.prototype.slice()的文档。 It said : 它说 :

For object references (and not the actual object), slice copies object references into the new array. 对于对象引用(而不是实际对象),切片将对象引用复制到新数组中。 Both the original and new array refer to the same object. 原始数组和新数组都引用同一对象。 If a referenced object changes, the changes are visible to both the new and original arrays. 如果引用的对象发生更改,则更改对新数组和原始数组均可见。

In this code, I use slice() to actual object but it still returns a reference 在这段代码中,我对实际对象使用slice() ,但它仍返回引用

var arObj = [
    { 'name': 'Jon',  'age': 24 },
    { 'name': 'Mark', 'age': 32 },
    { 'name': 'Kacy', 'age': 22 }
];

// use splice to copy array of objects into second variable
var ar2 = arObj.slice();

// modify property value in copy
ar2[1].name = 'Bill';

// view original (also modified)
console.log( arObj[1].name ); // Bill

And the second code, it doesn't: 第二个代码则没有:

let data = this.state.data.slice(); //If you don't have the slice function, it will return a reference.
console.log(this.state.data);
data.reverse();

if I try to reverse or change value of data, the value of (this.state.data) won't change. 如果我尝试反转或更改数据值,则(this.state.data)的值不会更改。 This is the structure of this.state.data: 这是this.state.data的结构:

https://i.stack.imgur.com/94emV.png https://i.stack.imgur.com/94emV.png

Thank you all for helping me, and sorry for my stupid bug. 谢谢大家的帮助,对于我的愚蠢错误也深表歉意。 The reverse() function won't affect the original array. reverse()函数不会影响原始数组。 It will be only affected if you mutate the value of one or more items in the reference array. 仅当您更改引用数组中一项或多项的值时,它才会受到影响。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM