gpt4 book ai didi

javascript - 在 JavaScript 中仅随机选择特定数组

转载 作者:行者123 更新时间:2023-12-03 04:47:54 26 4
gpt4 key购买 nike

我有多个数组,例如

 array1 = ["car","boot","bike"];
array2 = ["table","human","cat"];
array3 = ["boot","pc","iphone"];
array4 = ["boot","pc","iphone"];
array5 = ["bike","human","pet"];

这是随机获取数组的代码

  var card;
var rand;
var arr = [1,2,3,4,5];
rand = arr[Math.floor(Math.random() * arr.length)];

if(rand == 1){ card = array1; }else
if(rand == 2){ card = array2; }else
if(rand == 3){ card = array3; }else
if(rand == 4){ card = array4; }else
if(rand == 5){ card = array5; }

如何仅从没有值 "bike" 的数组中进行选择,或者如何仅从数组中第三个位置没有 "bike" 的数组中进行选择数组?

最佳答案

// We want one array containing all the data, so we only have to look at one place.
// Remember, an array can contain anything, including other arrays.
var words = [
["car","boot","bike"],
["table","human","cat"],
["boot","pc","iphone"],
["boot","pc","iphone"],
["bike","human","pet"]
];

// Let's make a function we can reuse to make things easier
var getArray = function( wordToIgnore ) {
// we need a random number here, but we also want to filter out any arrays that contain the word we have to ignore.
// SO we do the filter first, since if affects the random number.
var arraysToSearch = words.filter(function ( array ) {
// Standard filter function. We have to return true if the array should stay or false if it has to be removed.
// So we look at the index of the word we're searching for.
// If the word exists, we want to remove the array, else keep it.
return array.indexOf( wordToIgnore ) === -1;

// To get the 'bike' in 3rd position filter, we just need to update the filter function so it only looks at the 3rd position instead of any index.
// return array[2] === wordToIgnore;
});
// Now that we have the arrays we want to search in, we need a random array of those remaining arrays.
// If we multiply Math.random() with a number, we directly get the number we need.
// So with 3 arrays remaining, we want an index between 0 and 2
var index = Math.floor( Math.random() * (arraysToSearch.length) );
// Now that we have an index and an array filled with valid arrays, we can just return one;
return arraysToSearch[ index ];
};

// Let's use our function!
var randomArrayWithoutABike = getArray('bike');

关于javascript - 在 JavaScript 中仅随机选择特定数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42792123/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com