smus Posted April 7, 2018 Share Posted April 7, 2018 Sorry for stupid question. I can't understand the purpose of cloning an array in JS. Why do we need it? What is the difference between: let a = []; let b = a; and: let a = []; let b = a.slice(0); Link to comment Share on other sites More sharing options...
Ingolme Posted April 7, 2018 Share Posted April 7, 2018 In the first example, if you change a, b will also change because they're both pointing to the same thing. In the second example, both a and b can be changed independently of each other because they're two different arrays that merely have identical content. 1 Link to comment Share on other sites More sharing options...
iwato Posted April 8, 2018 Share Posted April 8, 2018 Ingolme: I do not understand your reply. In the second example. If I change a, so too will b change, because the value of a.slice(0) is determined by the value of a. in the first example. can I not assign a new value to b without affecting the value of a? Roddy Link to comment Share on other sites More sharing options...
Ingolme Posted April 9, 2018 Share Posted April 9, 2018 The slice() method creates a copy of the array, it does not create a reference to the array. After the copy has been made, it can be changed without modifying the original array. /* Two variables pointing to the exact same array */ var a = ["a", "b", "c"]; var b = a; b[0] = "d"; console.log(a[0]); // Prints "d" /* A variable containing a copy of the array in another variable */ var a = ["a", "b", "c"]; var b = a.slice(0); b[0] = "d"; console.log(a[0]); // Prints "a" Link to comment Share on other sites More sharing options...
smus Posted April 9, 2018 Author Share Posted April 9, 2018 Ingolme thank you! Link to comment Share on other sites More sharing options...
Recommended Posts
Create an account or sign in to comment
You need to be a member in order to leave a comment
Create an account
Sign up for a new account in our community. It's easy!
Register a new accountSign in
Already have an account? Sign in here.
Sign In Now