簡體   English   中英

測試一些基本的javascript代碼時出現意外輸出

[英]Unexpected output in testing some basic javascript code

我正在學習Javascript中的不同數組函數,我無法理解我編寫的測試array.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" } ]

新的contacts數組不應該只包含map函數返回的對象嗎?

我錯過了什么,我不確定它是什么。

您在返回參考tempJson因為其中的你在最終結果tempJson反映newContacts ,而不是clone你的tempJson然后返回克隆的對象。

 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;
}, {});

第二個參數{}.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); 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM