0

Save the contents of an array

If we have, for example, this code: var a=[2,8,7]; var b=a; a.shift(); document.write(b); The output will be "8,7". Well, I applied a change to "a", why exactly did "b" also change? And how to save the contents of the array before applying changes to the array itself?

11th Mar 2022, 12:26 PM
Eyad Al-Ahmar
Eyad Al-Ahmar - avatar
1 Respuesta
+ 2
var a = [2,8,7]; var b = a; // b refers to the address of a var c = [...a]; // creates an new array c that does no longer refer to a a.shift(); console.log("a", a) console.log("b", b); console.log("c", c); /* here some examples how to copy an array: https://holycoders.com/javscript-copy-array/ */
11th Mar 2022, 12:34 PM
Lisa
Lisa - avatar