用JavaScript中的函数交换对象的两个属性 [英] Swapping two properties of objects with function in javascript

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

问题描述

我正在尝试编写一个函数,该函数将接受两个对象(在这种情况下为人员),并且仅交换其两个属性.这是我为该人提供的功能:

I am trying to write a function that will take two objects, people in this case, and swap only two of their attributes. Here is my function for the Person:

function Person (tall, weight, gender, iq, favoriteColor) {
  this.tall = tall;
  this.weight = weight;
  this.gender = gender;
  this.iq = iq;
  this.favoriteColor = favoriteColor;
}

var joe = new Person("6-2", 180, "male", 130, "blue"); 
var bob = new Person("5-11", 150, "male", 120, "red");

所以我只想交换他们的智商和最喜欢的颜色.

So i want to swap JUST their IQs and favoriteColor.

到目前为止,我有:

function Swap(a, b) {
  var i = a;
  a = b;
  b = i;
  console.log(a, b);
}

这显然交换了它们的所有属性,但是我无法弄清楚如何只交换两个,并且仍然让它们作为对象登录.我已经尝试过:

This obviously swaps all their properties, but i cannot figure out how to swap just two and still have them log as objects. I have tried:

function Swap(a, b) {
  var a = a.iq + a.favoriteColor;
  var b = b.iq + b.favoriteColor;
  var i = a;
  a = b;
  b = i;
  console.log(a, b);
}

但这会在控制台中返回:

but this returns in the console:

120red 130blue.

从技术上讲,它交换了两个值,但是它们作为对象的结构不存在了,应该保留的其他三个属性也消失了.如何编写交换功能来做到这一点?

Technically it swapped the two values, but their structure as an object is gone and the other three properties that they were supposed to keep of their own are also gone. How do I write the swap function to do this?

谢谢!

推荐答案

这就是您想要的.您需要交换各个字段.您无法像您一样添加它们.另外,最好不要对已经声明的变量使用相同的名称,这太令人困惑了.

This is what you want. You need to swap the individual fields. You can't add them like you are doing. Also, it's best not to use the same name for variables that you've already declared, it's just too confusing.

function Swap(a, b) {
  var i = a.iq;
  a.iq = b.iq;
  b.iq = i;

  i = a.favoriteColor;
  a.favoriteColor= b.favoriteColor;
  b.favoriteColor = i;
  console.log(a, b);
}

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

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