【问题标题】:Question regarding swapping key/value of objects关于交换对象的键/值的问题
【发布时间】:2020-06-15 22:06:33
【问题描述】:

我想将 Jacob 的 key/value 内容与 Guillermo 的 key/value 内容交换

我可以将吉列尔莫换成雅各布,但反过来不行。

这是我的代码,只对了一半:

let students = {
  jacob: {
    classes: ["math", "chemistry", "english"],
    grade: 11,
    age: 16,
  },
  guillermo: {
    classes: ["history", "math", "physics"],
    grade: 12,
    age: 17,
  },
};
let temp = students.jacob;
students.guillermo = temp;
let temp1 = students.guillermo;
students.jacob = temp1;

console.log(students)

【问题讨论】:

  • 您应该首先分配两个temp 变量,然后才对对象属性进行分配。看看你现在拥有的中间两个作业,然后让它沉入其中......
  • 这能回答你的问题吗? How do I correctly clone a JavaScript object?

标签: javascript object key-value


【解决方案1】:

重新分配前需要复制

let students = {
  jacob: {
    classes: ["math", "chemistry", "english"],
    grade: 11,
    age: 16,
  },
  guillermo: {
    classes: ["history", "math", "physics"],
    grade: 12,
    age: 17,
  },
};
let temp = students.jacob;
let temp1 = students.guillermo;
students.guillermo = temp;
students.jacob = temp1;
console.log(students)

【讨论】:

    猜你喜欢
    • 2014-05-25
    • 1970-01-01
    • 1970-01-01
    • 2017-10-30
    • 2010-10-01
    • 2011-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多