简体   繁体   中英

How can I assign a random number to each object in an array in javascript?

Alright, so why am I asking this question? Because I am making a simple evolution simulator. In it, each creature will get a random amount of food each generation. The amount of of food each creature gets is crucial to if it survives or not. Since the only way I see it working is in an array(and I'm not good at arrays) can you help me find a way to assign these numbers to objects within the array?

I've looked through multiple websites for answers and none hit the dot. I also don't have any code so can you submit some code so I can see what I have to do?

You can just loop over the array and assign a random value to each creature. Example:

 let creatures = [ {name: "Bob", food: 0}, {name: "Alice", food: 0}, {name: "Steve", food: 0} ]; for(let creature of creatures) creature.food = Math.random(); // random number for food between 0-1 console.log(creatures); 

Simpley Do:

const creatures = [{
        name: "Bob"
    },
    {
        name: "Alice"
    },
    {
        name: "Steve"
    }
];
const creaturesWithFood = creatures.map((creature) => {
    return {
        food: Math.floor(Math.random() * 20),
        ...creature
    }
});
console.log(creaturesWithFood);

I've limit the numbers to be less than 20...you can change it as per your needs, Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM