今天我自己用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);
}
答案 0 :(得分:0)
如果你使用数组,生成和改组会更容易。数组有一个内置方法sort
,可以对它们的项进行排序。不幸的是,这些项目按照它们的文本表示进行排序,所以5在41之后。为了解决这个问题,你可以指定你自己的比较两个项目的比较回调函数。该比较在内部用于对整个数组进行排序。有关该流程的文档可以在on the Mozilla Developer Network找到。
var numbers = [];
for (var i = 0; i < 6; i++){
numbers.push(Math.round(Math.random() * 49));
}
numbers.sort(
function(a, b) {
return a - b;
});
alert(numbers);
&#13;
但是,此代码(如您自己的代码)可以生成重复项。一个更好的解决方案是采用数字1到49的数组,对该数组进行洗牌,然后从该数组中选择前5个数字。
生成一个数字为1到49的数组可以简单地使用上面代码片段中的for循环来完成,只有你可以将i
推送到数组而不是生成数字。
改组阵列有点困难,特别是做得对。幸运的是,关于该主题有this other question,它有很多很好的答案和很好的改组算法。
答案 1 :(得分:0)
可能有一种更有效的方法来处理这个问题。试试吧:
@Before("@annotation(authorized) && execution(* *())") // no string
public void authorize(JoinPoint joinPoint, Authorized authorized) {
helper(joinPoint,authorized,null);
}
// 1 argument, which is the string
@Before("@annotation(authorized) && execution(* *(..)) && args(str)")
public void authorize(JoinPoint joinPoint, Authorized authorized, String str) {
helper(joinPoint,authorized,str);
}
&#13;
答案 2 :(得分:0)
很简单。
var text =""
for (i=1;i<=7;i++) {
noppa = Math.round((Math.random() * 38) + 1);
text = text + " " + noppa;
}