smus 1 Posted April 7, 2018 Report 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); Quote Link to post Share on other sites
Ingolme 1,031 Posted April 7, 2018 Report 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 Quote Link to post Share on other sites
iwato 19 Posted April 8, 2018 Report 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 Quote Link to post Share on other sites
Ingolme 1,031 Posted April 9, 2018 Report 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" Quote Link to post Share on other sites
smus 1 Posted April 9, 2018 Author Report Share Posted April 9, 2018 Ingolme thank you! Quote Link to post Share on other sites
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.