最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Swap entire arrays in Javascript - Stack Overflow

programmeradmin5浏览0评论

When I try to make a function to swap 2 arrays, the original arrays are left unaltered.

function swap(x, y) {
    var temp = x; x = y; y = temp;
}

u=[1, 0];
v=[0, 1];
swap(u, v);
console.log(u);
console.log(v);

This results in u as [1, 0] and v as [0, 1]. The values haven't been changed after the function call to swap.

On the other hand, if I do this without a function call:

u=[1, 0];
v=[0, 1];
var temp = u;
u = v;
v = temp;
console.log(u);
console.log(v);

Then they're swapped correctly, with u as [0, 1] and v as [1, 0].

I thought Javascript arrays are passed by reference, not by value. Am I misunderstanding something here?

When I try to make a function to swap 2 arrays, the original arrays are left unaltered.

function swap(x, y) {
    var temp = x; x = y; y = temp;
}

u=[1, 0];
v=[0, 1];
swap(u, v);
console.log(u);
console.log(v);

This results in u as [1, 0] and v as [0, 1]. The values haven't been changed after the function call to swap.

On the other hand, if I do this without a function call:

u=[1, 0];
v=[0, 1];
var temp = u;
u = v;
v = temp;
console.log(u);
console.log(v);

Then they're swapped correctly, with u as [0, 1] and v as [1, 0].

I thought Javascript arrays are passed by reference, not by value. Am I misunderstanding something here?

Share Improve this question asked Feb 14, 2015 at 18:45 user3448821user3448821 2491 gold badge3 silver badges13 bronze badges 4
  • What is the expected output? – thefourtheye Commented Feb 14, 2015 at 18:46
  • u and v should be swapped. So u should be [0, 1] and v should be [1, 0]. I'll make it more clear in the question as well. – user3448821 Commented Feb 14, 2015 at 18:49
  • The fact that array's aren't copied doesn't mean they are passed "by reference". This is more similar to pass-by-pointer. – The Paramagnetic Croissant Commented Feb 14, 2015 at 18:50
  • "I thought Javascript arrays are passed by reference, not by value. Am I misunderstanding something here?" Yes, JavaScript only has pass-by-value. The type of values is irrelevant. – newacct Commented Feb 14, 2015 at 23:29
Add a ment  | 

6 Answers 6

Reset to default 8

JavaScript does not have the ability to pass a reference to the u and v variables themselves. So, no assignment to x or y in your swap() function will change what is assigned to u or v. JavaScript passes a reference to the object that u and v hold. Thus, you can't change the u and v variables from within swap(). You can change the contents of the object that they point to and thus properties of the object that u and v point to can be modified.

Since I have a C/C++ background, I think of what JavaScript does when passing objects as "pass by pointer". When you call swap(u, v), what is passed to the swap() function is a pointer to the array that u also points to. So, now you have two variables u and x both "pointing" at the same array. Thus, if you modify that actual array, then since u points at that same array, both will see the modification. But, nothing you do inside the swap() function can change what object u or v actually point to.


In JavaScript, the only way to change what object the original variables point to is to make them properties of an object and pass the object like this:

function swap(obj, x, y) {
    var temp = obj[x]; obj[x] = obj[y]; obj[y] = temp;
}

var container = {};
container.u = [1, 0];
container.v = [0, 1];
swap(container, "u", "v");
console.log(container.u);
console.log(container.v);

If you don't mind rewriting both arrays from scratch, you can copy all the contents of one array to a temporary, then copy one array over to the other and then copy the temporary array contents back to the first original. This is not very efficient and there is probably a better way to solve your original problem, but it can be done.

function swap(x, y) {
    // remove all elements from x into a temporary array
    var temp = x.splice(0, x.length);
    // then copy y into x
    x.push.apply(x, y);
    // clear y, then copy temp into it
    y.length = 0;
    y.push.apply(y, temp);
}

Getting the terminology on these "reference/value" questions is tricky, but I will do my best.

What you have for your Object / Array variables are really just references. Unlike C++, saying "x = y" does not actually copy the object's variables over to a new memory location. Internally, it's just copying a pointer location over. The language does not have constructions to "automatically recreate" something like an object or array in a new instance; if for some reason, you want to maintain two copies of an array, you will need to explicitly create it then copy over values (ie, = []; or = new Array(); or a copying function like = oldArray.map(...))

A little code example that might conceptually help. These same rules apply between objects and arrays.

a = {}; // In case you haven't seen it, this is like shorthand of "new Object();"
b = {};
c = b;
console.log(a === b); // false
console.log(b === c); // true
b.property = "hello";
console.log(c.property) // hello

Just like Java, JavaScript is pass-by-value only. Assigning to local variables in a function never has any effect on anything outside the function.

They are passed by reference, but they are also assigned by reference. When you write x = y you aren't modifying either of the arrays, you're just making your local variable x refer to the same array as y.

If you want to swap the array contents, you have to modify the arrays themselves:

function swap(x,y) {
    var temp = x.slice(0);
    x.length = 0;
    [].push.apply( x, y );
    y.length = 0;
    [].push.apply( y, temp ); 
}

Feb 2022 Solution to Swap 2 Entire Array Contents.

You can use destructuring to swap the 2 arrays:

let a = [  1,  2,  3, 4 ];
let b = ['a','b','c','d'];

[a,b] = [b,a];   // swap

console.log(a);  // ["a", "b", "c", "d"]
console.log(b);  // [1, 2, 3, 4, 5]

    let a = [  1,  2,  3, 4 ];
    let b = ['a','b','c','d'];
    
    [a,b] = [b,a];   // swap
    
    console.log(a);  // ["a", "b", "c", "d"]
    console.log(b);  // [1, 2, 3, 4, 5]

To swap 2 arrays you may use

Version 1

let arrA = [1,2,3,4];
let arrB = ['Eve', 'Bar', 'Foo'];

let tempArr = [arrA, arrB];  // constructing new array
arrA = tempArr [1];
arrB = tempArr [0];

Version 1 (shorthanded)

let arrA = [1,2,3,4];
let arrB = ['Eve', 'Bar', 'Foo'];
    
// RHS : construction a new array 
// LHS : destruction of array
[arrB, arrA ] = [arrA, arrB];  

Version 2 (spread operator)

let arrA = [1,2,3,4];
let arrB = ['Eve', 'Bar', 'Foo'];

let arrC = [...arrB]
arrB = [...arrA]
arrA = [...arrC]
发布评论

评论列表(0)

  1. 暂无评论