Home > Blockchain >  How can I create a method to /2 the array
How can I create a method to /2 the array

Time:12-18

I am learning to code and I am trying out this javascript object method course. I am currently stuck on this method. I want to have the array with three different numbers(2,5,10) to be /2. I do not understand why it is returning NaN. Thank you for reading.

//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());

CodePudding user response:

Try using .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;
        }
    }
}

CodePudding user response:

Maybe try .forEach to apply the same function to each element in an array

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

  • Related