最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

How do I prevent javascript from passing by reference when passing in an object's child - Stack Overflow

programmeradmin2浏览0评论

In my project there is a monochromatic screen you can write to and clear. Within the class I have these two lines of code for clearing the screen. the first pushes the current pixel values from the screen onto a stack so the clearscreen can be undone later. The second line clears the screen. the problem is that the undo stack is getting a reference to this.pixels rather than getting the value of it at the time.

this.pushUndo(this.pixels); //this.pixels is an array of ints
this.updateScreen(new Array(64*32)); //this.pixels changes at the end of this line but the undo stack shouldn't change its value

In my project there is a monochromatic screen you can write to and clear. Within the class I have these two lines of code for clearing the screen. the first pushes the current pixel values from the screen onto a stack so the clearscreen can be undone later. The second line clears the screen. the problem is that the undo stack is getting a reference to this.pixels rather than getting the value of it at the time.

this.pushUndo(this.pixels); //this.pixels is an array of ints
this.updateScreen(new Array(64*32)); //this.pixels changes at the end of this line but the undo stack shouldn't change its value
Share Improve this question asked Jan 11, 2019 at 0:25 anthius balaraw Xanthiusanthius balaraw Xanthius 1731 gold badge2 silver badges8 bronze badges 1
  • you can try cloning object – Nuthan Kumar Commented Jan 11, 2019 at 0:29
Add a ment  | 

2 Answers 2

Reset to default 5

You can use slice to create a shallow copy:

const pixels0 = [0, 1, 2, 3, 4, 5];
const pixels1 = pixels0.slice(0);

// modify only index 0 of copy.
pixels1[0] = 1;

console.log(pixels0);
// expected output: Array [0, 1, 2, 3, 4, 5]

console.log(pixels1);
// expected output: Array [1, 1, 2, 3, 4, 5]

If you need a deep copy, you can check What is the most efficient way to deep clone an object in JavaScript?

I usually do Object.assign when I need to clone values. Example:

const clone = Object.assign([], yourArray);

Can you show what is inside the updateScreen method in your question?

发布评论

评论列表(0)

  1. 暂无评论