简体   繁体   中英

JavaScript Reference array insert

I am novice to JavaScript but I know JavaScript does calls by value when passing primitives and calls by reference when passing objects.

var a = [4,5];
var temp = a;
console.log(a);    // [4,5]       OK
console.log(temp); // [4,5]       OK
temp = temp.push(6);  // Insert one more element into temp array

console.log(a);     // [4,5,6]  why so??
Console.log(temp);  // [4,5,6]  

I know this is because of reference got change . What should I do to avoid deep copy ?

If I change temp don't want to change original reference a, it should print [4,5].

If you want to copy it, you can use slice:

var temp = a.slice(0);

Edit: thanks to cuberto for pointing me out slice(0)

"I know JavaScript behavior is call by value in primitive value and call by reference in case of object."

Not exactly. In Javascript everything is passed by value all the time. If you pass an object, you actually pass a reference to the object, and that reference is passed by value.

Example:

var o = { name: 'first' };

// pass object reference to a function
use(o);

function use(x) {
  // change the reference
  x = { name: 'second' };
}

alert(o.name); // shows "first"

As the reference is passed by value to the function, changing the reference inside the function doesn't change the variable that was used to send the reference.

In your code you have only one array:

var temp = a; // copy the reference from a to temp

You have two variables that reference the same array, so any changes that you do to the array using one variable to access it will be visible when you look at the array using the other variable.

To get two separate arrays you have to specifically create a copy of it:

var temp = a.slice(0);

Note: Copying an array makes a shallow copy. That means that if you for example have an array of objects that you copy, you will have two arrays, but they will still share the same set of objects.

As you know, primitive values are passed by value, everything else is passed by reference. Primitives are boolean, number and string (and maybe consider null and undefined here). Everything else is an object and passed by reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM