在对象上交换两个属性的值

时间:2012-09-01 04:53:03

标签: javascript

我正在尝试创建一个简单的函数,它将在相同或不同的全局对象上交换两个属性的值。

object1 = {"key 1":"value 1"};
object2 = {"key 2":"value 2"};

swapValuesInObject ("object1['key 1']","object2['key 2']",true)
// should result in:
// object1 === {"key 1":"value 2"};
// object2 === {"key 2":"value 1"};

另一个例子:

object1 = {"key 1":"value 1", "key 2":"value 2"};

swapValuesInObject ("object1['key 1']","object1['key 2']",1===1)
// should result in:
// object1 === {"key 1":"value 2", "key 2":"value 1"};

到目前为止,这是我能够提出的,但并不多。挂断了如何进行任务。

function swapValuesInObject(property1, property2, condition) {
    if (condition) {
        // temp assignment
        var Obj1Value = property1;

        // do the switcheroo
        array1 = array2Value;
        array2 = array1Value;
    }
    return true;
};

这样做的正确方法是什么?

1 个答案:

答案 0 :(得分:4)

我会这样做:

var obj1 = {
    "key1" : "value1",
    "key2" : "Value2"
};
var obj2 = {
    "key3" : "value3",
    "key4" : "Value4"
};

function swap(sourceObj, sourceKey, targetObj, targetKey) {
    var temp = sourceObj[sourceKey];
    sourceObj[sourceKey] = targetObj[targetKey];
    targetObj[targetKey] = temp;
}

swap(obj1, "key1", obj1, "key2");
swap(obj1, "key1", obj2, "key4");