javascript - Changing an array value also changes value in another assigned array -


i learning javascript , in w3 schools' code editor try following code :

    <!doctype html> <html> <body>  <p id="demo"></p>  <script> var cars = ["saab", "volvo", "bmw"]; var newcars = []; newcars = cars; newcars[0] = "benz" document.getelementbyid("demo").innerhtml = cars[0]; </script>  </body> </html> 

i expected value : "saab" since made no changes cars array , change newcars array, yet output : "benz".

could please explain happening?

thanks

the value of variable "cars" contains "reference array" not "the array value". so, when go "var newcars = cars" copying reference only, means "cars" , "newcars" pointing same array. need make copy of array "cars" points , let "newcars" reference new copy. can clone array in different ways, done using libraries jquery (like here), underscore (like here) or without in here copying array value in javascript


Comments

Popular posts from this blog

database - VFP Grid + SQL server 2008 - grid not showing correctly -

jquery - Set jPicker field to empty value -

.htaccess - htaccess convert request to clean url and add slash at the end of the url -