Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swap two objects in JavaScript

I have the following code:

MyObject.prototype.doIt = function()
{
     var a = this.obj1;
     var b = this.obj2; 
}

How can i swap the values of this.obj1 and this.obj2 so obj1 becomes obj2 and obj2 becomes obj1.

!Note: Have in mind that i am not working with primitive types.

like image 471
Joro Seksa Avatar asked Apr 22 '13 16:04

Joro Seksa


People also ask

How do you swap objects in JavaScript?

You can swap any number of objects or literals, even of different types, using a simple identity function like this: var swap = function (x){return x}; b = swap(a, a=b); c = swap(a, a=b, b=c); This works in JavaScript because it accepts additional arguments even if they are not declared or used.

How do you swap a and b in JavaScript?

Here, a new es6 feature, called destructuring assignment [a, b] = [b, a] , is used to swap the value of two variables. If [a, b] = [1, 2, 3] , the value of a will be 1 and value of b will be 2. First a temporary array [b, a] is created. Here the value of [b, a] will be [2, 4] .

How do you write a swap function in JavaScript?

function swap(x,y){ var t = x; x = y; y = t; } console. log(swap(2,3));

How can I swap two values without using third variable in JavaScript?

Example: Suppose, there are two numbers 25 and 23. X= 25 (First number), Y= 23 (second number) Swapping Logic: X = X + Y = 25 +23 = 48 Y = X - Y = 48 - 23 = 25 X = X -Y = 48 - 25 = 23 and the numbers are swapped as X =23 and Y =25.


2 Answers

You can swap any number of objects or literals, even of different types, using a simple identity function like this:

var swap = function (x){return x};
b = swap(a, a=b);
c = swap(a, a=b, b=c);

This works in JavaScript because it accepts additional arguments even if they are not declared or used. The assignments a=b etc, happen after a is passed into the function.

like image 103
dansalmo Avatar answered Oct 05 '22 23:10

dansalmo


Use a temporary variable to hold the contents of one of the objects while swapping:

var tmp = this.obj1;
this.obj1 = this.obj2;
this.obj2 = tmp;
like image 31
Chris Hanson Avatar answered Oct 05 '22 23:10

Chris Hanson