作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
今天我自己用 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/
我是一名优秀的程序员,十分优秀!