Jump to content

Recommended Posts

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.

  • Thanks 1
Link to post
Share on other sites

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 post
Share on other sites

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 post
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...
×
×
  • Create New...