javascript 如何编写一个函数,从数组中随机选择一个名称,而不选择最后一个元素

cygmwpex  于 2023-01-24  发布在  Java
关注(0)|答案(3)|浏览(78)

我正在编写一个函数,从数组中随机选择一个项目插入到一个输出中,该输出显示“”随机选择的名称”正在支付今天的午餐费用!"。从我的Angular 来看,一切看起来都很好,但我不明白为什么它不运行。Udemy也不接受提供的解决方案ScreenShot from Udemy js editor

var names = ["Hameed", "David", "Maleek", "Ola"];

function whosPaying(names){
    var output;
    var arr_length = names.length;
    var index = Math.floor(Math.random() * (arr_length-1));
    output = names[index] + " is going to pay for lunch today!";
     
    return output;
}
bjp0bcyl

bjp0bcyl1#

这里我重新创建了遗留的Math.random函数来支持in between range,然后修复了range[0,arr_length-1],这应该会对您的情况起到很好的作用。
Clarification: He's also never going to get other index but 0 because the usual数学随机returns a value in [0-1]! That's why I had to recreate the数学随机method for him and then just fix the new range to [0-arr_length-1]. And that guarantees him to get each time a random index in the correct range.
此外,您还需要调用您的函数以获得结果!

(function(){
  const originalMathRandom = Math.random;
  Math.random = function(min=0, max=1) {
    return originalMathRandom() * (max - min) + min;
  }
}());

var names = ["Hameed", "David", "Maleek", "Ola"];

function whosPaying(names){
    var output;
    var arr_length = names.length;
    var index = Math.floor(Math.random(0, arr_length-1));
    output = names[index] + " is going to pay for lunch today!";
     
    return output;
}

console.log( whosPaying(names) );
p8h8hvxi

p8h8hvxi2#

这个管用!

var names = ["Hameed", "David", "Maleek", "Ola"];

function whosPaying(names){

    var arr_length = names.length;
    var posInArray = Math.floor(Math.random() * arr_length );
    var randomPerson = names[posInArray];
    var output = randomPerson + " is going to buy lunch today!";

    return output
    
}

whosPaying(names);
gdx19jrr

gdx19jrr3#

函数whosPaying(名称){

var Numberofpeople= names.length;
var randompersonposition = Math.floor(Math.random() * Numberofpeople);
var randomperson = names[randompersonposition];

return randomperson + " is going to buy lunch today!";

}

相关问题