简体   繁体   English

如何在JavaScript中为数组中的每个对象分配一个随机数?

[英]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 :) 我将数字限制为小于20 ...您可以根据需要进行更改,希望这会有所帮助:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在JavaScript中生成随机数并将其分配给我的变量数组? - How to generate a random number and assign it to my variable array in JavaScript? 如何为数组中另一个数组中的对象中的每个对象分配唯一键和线性键? - How can I assign unique and linear key for each object within an array that's in an object within another array? 如何将随机 integer 分配给数组 JavaScript 中的每个 object - How to assign a random integer to every object in an array JavaScript 如何将对象数组分配给数组? - How can i assign array of object to array? 如何在javascript中过滤和修改数组中的每个对象? - How can i filter and modify each object in array in javascript? 如何为数组中的每个项目分配随机颜色? - How to assign a random colour for each item in an array? 如何使用JavaScript for循环在每行上显示新的随机数? - How can I display a new random number on each line with a JavaScript for loop? 如何将JavaScript数组分配给Ftllist? - How can i assign javascript array to Ftllist? 如何使用JavaScript函数为每个div分配坐标值? - How can I assign each div a coordinate value with a javascript function? 如何以每个随机数具有不同值的方式在多个位置调用随机数? - How can I call a random number in multiply places in a way that each random number has a different value?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM