<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title></title> </head> <body> <script> var str = ''; var add =[1,2,3,4,5,6,8,9]; var newArr = [1,2,3,4,5,6,7,8,9,-1,-2,-3,-4,-5,-6,-7,-8,-9]; function getN(arr){ return Math.floor(Math.random() * arr.length + 1)-1; } var resultArr = []; var log = ''; function randNum(){ for(var i =0;i<80;i++){ var num = newArr[getN(newArr)];//隨機取了一個數字 Math.abs(aaa); if(num < 0){//負數 if(inArray(Math.abs(num),resultArr) != -1 && (repeatNum(num,resultArr) != repeatNum(Math.abs(num),resultArr))){//正數存在,並且正負是不成對 resultArr.push(num); } else {//正數不存在 resultArr.push(-num); } } else {//正數 if((repeatNum(-num,resultArr) == repeatNum(Math.abs(num),resultArr))){//正數存在,並且正負成對 resultArr.push(num); } else {//正數不存在 resultArr.push(-num); } } } str += resultArr.join(',') + '|' + check(resultArr) + '<br>'; } function getArr(n){ for(var i = 0; i<n; i++){ resultArr.length =0; randNum(); } } //查找索引 function inArray(t,arr){ if(arr.indexOf){ return arr.indexOf(t); } for(var i=arr.length;i--;){ if(arr[i]===t){ return i*1; } }; return -1; } //刪除數組某一個 function deleInArray(n,arr){ if(n<0) return false; arr.splice(n,1); } //重複次數 function repeatNum(t,arr){ var times = 0; for(var i = 0;i<arr.length;i++){ if(t == arr[i]){ times ++; } } return times; } function addFunc(){ var newNum = newArr[getN(add)]; if(inArray(newNum,resultArr) == -1){//不存在 resultArr.push(newNum); } else { addFunc(); } } //檢查數據 function check(arr){ var maxNum = 0; var str = ''; for(var i = 0; i<arr.length; i++){ maxNum += arr[i]; if(maxNum >= 45){ str = '不可用' + '|' + '第' + i + '個數字' + '|' + '數字是:' + arr[i]; break; } else { str = '可用'; } } return str; } getArr(100); document.write(str); </script> </body> </html>
目的是產生,數組長度是80的序列。正負相抵消,最後只剩下1到9就看成是中獎!注意要先產生正的才能出現負的!html