0

Before I get into the problem, I already fixed it and I'll show how. I just wonder why is this happening.

I'm new to javascript and I have a dictionary containing mouse events like this:

let mouseInputs = {mousePosition: [], mouseDown: []};

I have added 3 event listeners (I want to be able to detect the mouse position when they click down and when they click up)

canvas.addEventListener('mousemove', mousePosition);
canvas.addEventListener('mousedown', mouseDown);
canvas.addEventListener('mouseup', mouseUp);

These are the functions that will be called when the user clicks mouse buttons. When they click down, I want the mouseInputs[mouseDown] value to be the same as mouseInputs[mousePosition]. When the user lifts the mouse button (mouseUp) I just want to empty mouseInputs[mouseDown] as the user stopped clicking.

function mouseDown() {
  // 1 means left button for mouse
  if (event.buttons === 1) {

  mouseInputs.mouseDown = mouseInputs.mousePosition;
  };
};

function mouseUp() {
  // mouse.buttons will always turn out even when the event is called by left button up
  if (event.buttons%2 === 0) {

    console.log(mouseInputs.mousePosition);
    mouseInputs.mouseDown.length = 0;
    console.log(mouseInputs.mousePosition);

  };
};

The problem is that when I run the code, the console logs display this:

(2) [439, 353]
[]

Which means after I emptied mouseDown it also emptied mousePosition... I fixed this by just reassigning mouseDown instead of changing its length:

  console.log(mouseInputs.mousePosition);
  mouseInputs.mouseDown = [];
  console.log(mouseInputs.mousePosition);

Which then shows mousePosition doesn't change at all (which is how it should be)

(2) [312, 238]
(2) [312, 238]

My question is why does changing the variable's length also affected the other variable but just changing the value itself didn't? Thank you very much in advance.

  • because pointers ..... https://www.samanthaming.com/tidbits/70-3-ways-to-clone-objects/ – Goofballtech Jun 13 '20 at 17:47
  • You have two references to the same array. You really wanted to have a copy. So use `a = b.slice()` or `a = [...b]`, not `a = b`. – trincot Jun 13 '20 at 17:47

0 Answers0