gpt4 book ai didi

JavaScript 乐透号码选择器 - 需要按数字顺序显示结果

转载 作者:行者123 更新时间:2023-11-28 07:14:02 25 4
gpt4 key购买 nike

今天我自己用 JavaScript 编写了第一个程序(耶!)。它是一个乐透号码选择器,可以从 1 到 49 之间随机选择我的六个彩票号码。虽然它看起来工作正常,没有重复,但我希望程序按数字顺序将数字打印到警报框中。任何帮助,将不胜感激。我的代码如下:

var firstNumber = Math.round(Math.random() * 49);
var secondNumber = Math.round(Math.random() * 49);
var thirdNumber = Math.round(Math.random() * 49);
var fourthNumber = Math.round(Math.random() * 49);
var fifthNumber = Math.round(Math.random() * 49);
var sixthNumber = Math.round(Math.random() * 49);


if(firstNumber === secondNumber || firstNumber === thirdNumber ||
firstNumber === fourthNumber || firstNumber === fifthNumber ||
firstNumber === sixthNumber || firstNumber === 0) {
Math.round(Math.random() * 49);
} else if(secondNumber === firstNumber || secondNumber === thirdNumber ||
secondNumber === fourthNumber || secondNumber === fifthNumber ||
secondNumber === sixthNumber || secondNumber === 0) {
Math.round(Math.random() * 49);
} else if (thirdNumber === firstNumber || thirdNumber === secondNumber ||
thirdNumber === fourthNumber || thirdNumber === fifthNumber ||
thirdNumber === sixthNumber || thirdNumber === 0) {
Math.round(Math.random() * 49);
} else if (fourthNumber === firstNumber || fourthNumber === secondNumber ||
fourthNumber === thirdNumber || fourthNumber === fifthNumber ||
fourthNumber === sixthNumber || fourthNumber === 0) {
Math.round(Math.random() * 49);
} else if(fifthNumber === firstNumber || fifthNumber === secondNumber ||
fifthNumber === thirdNumber || fifthNumber === fourthNumber ||
fifthNumber === sixthNumber || fifthNumber === 0){
Math.round(Math.random() * 49);
} else if(sixthNumber === firstNumber || sixthNumber === secondNumber ||
sixthNumber === thirdNumber || sixthNumber === fourthNumber ||
sixthNumber === fifthNumber || sixthNumber === 0) {
Math.round(Math.random() * 49);
} else {
alert(firstNumber + ", " + secondNumber + ", " + thirdNumber + ", " +
fourthNumber + ", " + fifthNumber + ", " + sixthNumber);
}

最佳答案

可能有更有效的方法来解决这个问题。尝试一下:

var min = 1,
max = 49,
total = 6,
nums = [];

// For [total] times
for(var i=0; i<total; i++){
// Generate a random number between [min] and [max]
var num = Math.floor( Math.random() * max + min );
// If number already there, repeat
if( nums.indexOf(num) > -1 ){ i--; continue; }
// Add the number to the array
nums.push(num);
}

// Sort and show the resulting array, comma separated
alert( nums.sort(sortNumber).join(', ') );

function sortNumber(a,b) {
return a - b;
}

关于JavaScript 乐透号码选择器 - 需要按数字顺序显示结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31035597/

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