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.
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.
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] .
function swap(x,y){ var t = x; x = y; y = t; } console. log(swap(2,3));
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.
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.
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;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With