簡體   English   中英

map function 返回未定義

[英]map function return undefined

在下面,您會看到一個簡單的 map function 用於數組,我無法弄清楚為什么我在調用index[0]時出現undefined

當我調用return index時,我得到了數字數組。 所以他們存在!

資源:

 let aRa = [ { hero: "troll", age: 12, hair: "red" }, { hero: "rikky", age: 11, hair: "purple" }, { hero: "techies", age: 40, hair: "yellow" } ] let joyRide = aRa.map(function(item, index, array) { return index[0]; }); console.log(joyRide)

源代碼圖片:

源代碼

傳入Array.prototype.map()的回調的第二個參數獲取一個數字。 您正在嘗試索引一個數字並獲得未定義。

Array.prototype.map()的回調 function 的第二個參數是具有數值的索引,在它們上使用索引將始終返回undefined

要訪問數組中每個 object 的第一個鍵,您可以使用解構Destructuring assignment嘗試以下操作:

 let aRa = [ {hero:"troll", age:12, hair:"red",}, {hero:"rikky", age:11, hair:"purple"}, {hero:"techies", age:40, hair:"yellow"}, ] let joyRide = aRa.map(({hero}) => hero); console.log(joyRide)

如果要提取鍵,可以使用 object 解構賦值 hen 映射來提取鍵引用的單個鍵值對。

 const heroes = [ { hero: "troll", age: 12, hair: "red" }, { hero: "rikky", age: 11, hair: "purple" }, { hero: "techies", age: 40, hair: "yellow" } ] const names = heroes.map(({ hero }) => hero); const ages = heroes.map(({ age }) => age); const hairColors = heroes.map(({ hair }) => hair); console.log(`Names: ${names.join(', ')}` ); console.log(`Ages: ${ages.join(', ')}` ); console.log(`Hair Colors: ${hairColors.join(', ')}`);

如果想要數組中的第一項,也可以使用 object 解構。

 const heroes = [ { hero: "troll", age: 12, hair: "red" }, { hero: "rikky", age: 11, hair: "purple" }, { hero: "techies", age: 40, hair: "yellow" } ] const [ first ] = heroes; console.log(first); const [ { hero: firstName } ] = heroes; console.log(firstName);

如果您的意思是獲得第一個元素的“英雄”,您可以通過

console.log(aRa[0].hero)

如果你想在一個新數組中獲取所有項目的英雄元素和 map 它,你應該這樣做

let aRa = [
  { hero: "troll"   , age: 12 , hair: "red"    },
  { hero: "rikky"   , age: 11 , hair: "purple" },
  { hero: "techies" , age: 40 , hair: "yellow" }
]

let joyRide = [];
for (i = 0; i<aRa.length; i++) {
  joyRide.push(aRa[i].hero);
}

console.log(joyRide)

Map function 它會根據 map 被調用的數組的長度自動執行循環在你的情況下,這對你有用..

let joyRide = aRa.map(function(item, index, array) {
  return item; 
});

如果你想獲得英雄數組

 let joyRide = aRa.map(function(item, index, array) {
      return item.hero;
    });

解釋

/* 當第一次循環執行時 */

item將具有值{ hero: "troll", age: 12, hair: "red" }

索引的值為0

數組將具有價值

[
  { hero: "troll"   , age: 12 , hair: "red"    },
  { hero: "rikky"   , age: 11 , hair: "purple" },
  { hero: "techies" , age: 40 , hair: "yellow" }
]

/* 當第二次循環執行時 */

item有值{ hero: "rikky", age: 11, hair: "purple" }

index的值為1

數組將具有價值

[
  { hero: "troll"   , age: 12 , hair: "red"    },
  { hero: "rikky"   , age: 11 , hair: "purple" },
  { hero: "techies" , age: 40 , hair: "yellow" }
]

依此類推,直到數組的長度..

暫無
暫無

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

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