在 JavaScript 中从数组中随机选取索引
问题
我们需要编写一个JavaScript函数,它接受一个数字数组arr,它可能包含重复项作为第一个参数和一个存在于数组中的整数作为第二个参数。
该函数应该返回数组中存在数字的索引,并且由于该数字可能在数组中多次存在,我们必须随机选择一个索引并返回该索引。
例如,如果函数的输入是-
const arr = [5, 3, 6, 7, 3, 4, 2, 3]; const num = 3;
那么输出应该是-
const output = 4;
输出说明:
数字3存在于数组中的索引1、4和7处,并且由于我们必须随机选择任何索引,因此输出可以是1中的任何一个。
示例
此代码将是-
const arr = [5, 3, 6, 7, 3, 4, 2, 3];
const num = 3;
Array.prototype.pick = function(target) {
const targets = []
this.findTarget(0, this.length, target, targets);
return targets[Math.floor(Math.random() * targets.length)];
};
Array.prototype.findTarget = function(start, end, target, targets) {
if(start + 1 === end || start === end) {
if(this[start] === target) targets.push(start);
return;
}
let j = start + Math.floor((end - start)/2);
this.findTarget(start, j, target, targets);
this.findTarget(j, end, target, targets);
};
console.log(arr.pick(num));输出结果控制台中的输出将是-
4
热门推荐
10 对患者生日祝福语简短
11 结婚祝福语简短装备
12 周岁祝福语学生文案简短
13 订婚领证祝福语简短精辟
14 导师获奖祝福语大全简短
15 新婚购房祝福语简短精辟
16 牛年祝福语简短的爱人
17 送芒果的祝福语简短
18 送给学长毕业祝福语简短