在对象上交换两个属性的值 [英] Swap value of two properties on object(s)

查看:328
本文介绍了在对象上交换两个属性的值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to make a simple function that will swap the values of two properties on the same or different global objects.

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

这是我迄今为止所能提出的,但并不多。挂断了如何进行任务。

Here's what I've been able to come up with so far, but it's not much. Getting hung up on how to do the assignment.

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

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

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

What's the proper way to do this?

推荐答案

我会这样做:

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");

这篇关于在对象上交换两个属性的值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆