[英]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.