测试一些基本JavaScript代码时出乎意料的输出



我正在学习JavaScript中不同数组函数的学习,我无法理解我编写的基本代码的输出,该代码为test arnay.map((。

let contacts = [{
  "firstName": "Jim",
  "lastName": "Smith"
}, {
  "firstName": "Laura",
  "lastName": "Bush"
}, {
  "firstName": "Adam",
  "lastName": "Shaw"
}];
let tempJson = {};
const newContacts = contacts.map(contact => {
//tempJson = {}
tempJson[contact.firstName] = contact.lastName
console.log(tempJson);
return tempJson;
});
console.log(newContacts);

预期输出

//tempJson
{ "Jim": "Smith" }
{ "Jim": "Smith", "Laura": "Bush" }
{ "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" }
//newContacts
[ { "Jim": "Smith", }, 
  { "Jim": "Smith", "Laura": "Bush"}, 
  { "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" } ]

实际输出

//tempJson
{ "Jim": "Smith" }
{ "Jim": "Smith", "Laura": "Bush" }
{ "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" }
//newContacts
[ { "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" }, 
  { "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" }, 
  { "Jim": "Smith", "Laura": "Bush", "Adam": "Shaw" } ]

新联系人数组不应该仅由映射函数返回的对象组成?

我缺少某些东西,我不确定是什么。

您正在返回对tempJson的引用,因为您在tempJson中的最终结果反映了newContacts,而是clone您的CC_4,然后返回克隆对象。

let contacts = [{
    "firstName": "Jim",
    "lastName": "Smith"
  }, {
    "firstName": "Laura",
    "lastName": "Bush"
  }, {
    "firstName": "Adam",
    "lastName": "Shaw"
  }];
  
  let tempJson = {};
  
  const newContacts = contacts.map(contact => {
    let clonedObj = {};
    tempJson[contact.firstName] = contact.lastName
    Object.assign(clonedObj, tempJson);
    return clonedObj;
  });
  
  console.log(newContacts);

ps:reduce更合适,正如其他人所指向的。

let contacts = [{
    "firstName": "Jim",
    "lastName": "Smith"
  }, {
    "firstName": "Laura",
    "lastName": "Bush"
  }, {
    "firstName": "Adam",
    "lastName": "Shaw"
  }];
  
const output = contacts.reduce((accu, {firstName, lastName}, i) => {
    accu.push({...accu[i-1], [firstName]: lastName });
    return accu;
}, []);
console.log(output);

.map()函数旨在使用数组,并将每个元素转换为新数组的相应元素值。看来,您想做的是从数组的元素中构建一个新的对象,因此对于.map()来说,这并不是真正的工作。更通用的.reduce()函数会更好:它使您可以通过数组的元素进行迭代进行任何形式的值。

在这种情况下,您可以使用.reduce()如下:

const newContacts = contacts.reduce(function(result, contact) {
  result[contact.firstName] = contact.lastName;
  return result;
}, {});

第二个参数 {} to .reduce()是起始值。它已作为第一个参数传递给每个迭代的回调函数,回调负责返回更新的值。

而不是使用reduce

let contacts = [{
  "firstName": "Jim",
  "lastName": "Smith"
}, {
  "firstName": "Laura",
  "lastName": "Bush"
}, {
  "firstName": "Adam",
  "lastName": "Shaw"
}];
const newContacts = Object.entries(contacts.reduce((acc, { firstName, lastName }) => {
  acc[firstName] = lastName;
  return acc;
}, {})).map(([k, v]) => ({[k]: v}));
console.log(newContacts);

最新更新