假设我有3个对象数组:
const fruits = [
{name: "Banana"},
{name: "Apple"},
{name: "Peach"}
]
const car = [
{name: "Audi"},
{name: "Bentley"}
]
const books = [
{name: "Alice in wonderland"},
{name: "Deep in the dark"},
{name: "Hunting Show"}
]一个临时数组,我将在其中存储数组中的随机对象。
const tempArray = []我想从随机数组中获取随机对象。
我从水果或汽车阵列中获得随机对象的概率为80%
从图书数组中获得随机对象的概率为20%
随机机会是80%的->随机对象,来自数组水果的随机对象被推到tempArray,而tempArray应该有带有香蕉的对象。
随机机会是20% ->随机对象从数组书籍被推到tempArray和tempArray应该有一个名为“狩猎秀”的对象
我如何在javascript中做到这一点?
发布于 2020-10-25 10:36:27
首先,我们结合水果和汽车阵列。然后我们生成一个从1到100的随机数。从1到80的数字将从fruitsAndCar数组中选择一个随机元素,而从81到100的数字将从图书数组中选择一个随机元素。
const fruits = [
{name: "Banana"},
{name: "Apple"},
{name: "Peach"}
]
const car = [
{name: "Audi"},
{name: "Bentley"}
]
const books = [
{name: "Alice in wonderland"},
{name: "Deep in the dark"},
{name: "Hunting Show"}
]
const tempArray = []
const fruitsAndCar = fruits.concat(car);
let randomNumber = Math.floor((Math.random() * 100) + 1); // 1 to 100
if (randomNumber <= 80) {
let randomIndex = Math.floor(Math.random() * fruitsAndCar.length); // 0 to 4
tempArray.push(fruitsAndCar[randomIndex]);
} else {
let randomIndex = Math.floor(Math.random() * books.length); // 0 to 2
tempArray.push(books[randomIndex]);
}
console.log('tempArray: ' + JSON.stringify(tempArray));https://stackoverflow.com/questions/64522542
复制相似问题