9

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

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;
};

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

4

3 回答 3

10

使用 ES6 解构,您现在可以在没有临时变量的情况下进行交换。这不仅适用于交换变量值,也适用于[a, b] = [b, a]涉及对象属性的更复杂的表达式,如下所示[obj.key1, obj.key2] = [obj.key2, obj.key1]:为避免更多冗余,您需要使用交换功能:

function swap(obj, key1, key2) {
   [obj[key1], obj[key2]] = [obj[key2], obj[key1]];
}
swap(obj, 'key1', 'key2');

同样的想法适用于两个对象和两个键:

function swap(obj1, key1, obj2, key2) {
   [obj1[key1], obj2[key2]] = [obj2[key2], obj1[key1]];
}
swap(obj1, 'key1', obj2, 'key2');
于 2017-08-11T14:17:07.470 回答
6

我会这样做:

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");
于 2012-09-01T05:04:07.297 回答
0

简单来说,

var obj = {
 "key1": "value1",
 "key2": "Value2" 
}

value1分配给key2 & value2分配给key1

[obj['key1'], obj['key2']] = [obj['key2'], obj['key1']];
于 2021-09-22T05:35:49.493 回答