【问题标题】:How can I create a method to /2 the array如何创建 /2 数组的方法
【发布时间】:2022-01-20 20:32:17
【问题描述】:

我正在学习编码,并且正在尝试这个 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());

【问题讨论】:

  • 您尝试在数组上使用/,但/ 仅对数字有意义。您需要遍历allEggsTime 中的每个项目并将它们相除,然后将结果推送到新数组中(或更新当前索引处的项目以保存新的计算值)

标签: javascript arrays object methods


【解决方案1】:

也许尝试 .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

【讨论】:

  • 这个返回未定义。我不知道为什么
  • .forEach() 不返回任何内容(它返回 undefined)。您需要使用.map() 来返回一个新数组
  • 对不起,试试这个。常量 eggHatchTime2km = 2 常量 eggHatchTime5km = 5 常量 eggHatchTime10km = 10 allEggsTime = [eggHatchTime2km,eggHatchTime5km,eggHatchTime10km]; console.log(allEggsTime); const pokemonGoCommunityDay = { eventBonuses: { calculateEggHatchTime() { let halfEggsTime = [] allEggsTime.forEach((egg,index) => {halfEggsTime[index] = egg/2}) return halfEggsTime; } } } console.log(pokemonGoCommunityDay); console.log(pokemonGoCommunityDay.eventBonuses.calculateEggHatchTime())
【解决方案2】:

尝试使用 .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;
        }
    }
}

【讨论】:

    猜你喜欢
    • 2010-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-12-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多