我正在學習編碼,我正在嘗試這個 javascript 物件方法課程。我目前堅持這種方法。我想讓具有三個不同數字(2,5,10)的陣列為/2。我不明白為什么它回傳 NaN。感謝您的閱讀。
//Eggs hatch time
eggHatchTime2km = 2
eggHatchTime5km = 5
eggHatchTime10km = 10
allEggsTime = [eggHatchTime2km,eggHatchTime5km,eggHatchTime10km];
console.log(allEggsTime); //reads out 2,5,10
const pokemonGoCommunityDay = {
eventBonuses: {
calculateEggHatchTime() {
return allEggsTime/2; //return NaN
//return eggHatchTime2km,eggHatchTime5km,eggHatchTime10km/2; //return the value of the last variable(10km) but not 2km and 5km
},
}
}
console.log(pokemonGoCommunityDay);
console.log(pokemonGoCommunityDay.eventBonuses.calculateEggHatchTime());
uj5u.com熱心網友回復:
嘗試使用 .map()
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map
const pokemonGoCommunityDay = {
eventBonuses: {
calculateEggHatchTime() {
const halfEggsTime = allEggsTime.map(egg=>egg/2)
return halfEggsTime;
}
}
}
uj5u.com熱心網友回復:
也許嘗試 .forEach 將相同的函式應用于陣列中的每個元素
const pokemonGoCommunityDay = {
eventBonuses: {
calculateEggHatchTime() {
const halfEggsTime = allEggsTime.forEach(egg=>egg/2)
return halfEggsTime;
}
}
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384847.html
標籤:javascript 数组 目的 方法
下一篇:如何使用js過濾表中ul的li?
