我有以下代码,想要更改名称或switsch值,但我不知道它是如何工作的并且很容易
var employees = [{firstName: "Richter", lastName: "Johnas"},
{firstName: "Leibig", lastName: "Linda"},
{firstName: "Schneider", lastName: "Mariane"},
];
console.log("\n> Should display [{firstName: 'Johnas', lastName: 'Richter'}, {firstName: 'Linda', lastName: 'Leibig'}, {firstName: 'Mariane', lastName: 'Schneider'}]");
console.log(revertFirstNamesAndLastNames(employees));`
我想将firstname更改为lastname,将lastname更改为firstname。
答案 0 :(得分:0)
要达到预期效果,请使用以下使用地图
的选项
var employees = [{firstName: "Richter", lastName: "Johnas"},
{firstName: "Leibig", lastName: "Linda"},
{firstName: "Schneider", lastName: "Mariane"},
];
employees.map((v,i)=>{
let fname = v.firstName
v.firstName = v.lastName
v.lastName = fname
})
console.log(employees);

代码示例 - https://codepen.io/nagasai/pen/rvvpwN?editors=1010
选项2:
使用forEach来实现预期的结果,唯一的区别是forEach()只返回什么,但map()返回一个全新的数组。
有关详细信息,请查看此链接 - JavaScript: Difference between .forEach() and .map()
var employees = [{firstName: "Richter", lastName: "Johnas"},
{firstName: "Leibig", lastName: "Linda"},
{firstName: "Schneider", lastName: "Mariane"},
];
employees.forEach((v)=>{
let fname = v.firstName
v.firstName = v.lastName
v.lastName = fname
})
console.log(employees)