-2

Javascript Question. I am pretty new to javascript so pardon me if anything is not clear.

Please play following example at (right click) "inspect --> Console".

Example:

o = [1,2,3];
y = o;
delete y[0];
y;// result: [undefined × 1, 2, 3]
o;// result: [undefined × 1, 2, 3]

Is it possible that the delete of y does not affect o? Here I made y equal to o. I just wanted to delete the first item of y but not o. However, o changes with y together. I wonder if it is possible to prevent o being changed even I change y?

WCMC
  • 1,602
  • 3
  • 20
  • 32

1 Answers1

3

You can do:

y = o.slice()

Then that'll give you your own copy.

You can even use:

y = [...o]

depending on the browser support.

Bill Criswell
  • 32,161
  • 7
  • 75
  • 66