Swap two objects in JavaScript

折月煮酒 提交于 2019-12-07 02:30:41

问题


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.


回答1:


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.




回答2:


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;



回答3:


You can swap the properties easily enough:

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

That obj1 and obj2 are not primitive types is irrelevant. You don't actually need two variables:

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

However, if any references to this.obj1 or this.obj2 already exist outside this code, they won't be swapped.

In terms of swapping this.obj1 and this.obj2 everywhere (including existing references), I don't think that can be done completely. You could strip out all properties of, say, this.obj1 (saving them somewhere), add in the properties from this.obj2, and then do the same for this.obj2. However, you won't be able to swap the prototypes, so objects cannot fundamentally swap identities.




回答4:


Here is an example with concrete objects, say your original objects are 2 divs, div1 and div2.

To swap them,

var temp1 = div1;
var temp2 = div2;

div1 = temp2;
div2 = temp1;



来源:https://stackoverflow.com/questions/16151682/swap-two-objects-in-javascript

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!