Math.random()的值是小于1的,那么用floor函数就不可能得到1,即结果中不会存在10,但是个人调试的结果3次第一个值都是10,请问是为什么?(注:按照题目应该用round)
如下是我的代码:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Math </title> <script type="text/javascript"> var myarr=[]; var i=0; var num; var j; num = Math.floor(Math.random()*10); myarr[0]=num; while(myarr.length<10) { num = Math.floor(Math.random()*10); for(j=0;j<myarr.length;j++) { if(num==myarr[j]) { break; } } if(j==myarr.length) { myarr[j]=num; } } document.write(myarr.length+"</br>"); for (var k =0; k < myarr.length; k++) { document.write(myarr[k]+"</br>"); } </script> </head> <body> </body> </html>
被自己蠢哭,第一个是数组的长度,调试了太久,忘记了!
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Math </title> <script type="text/javascript"> var myarr=[]; var i=0; var num; var j; num = Math.floor(Math.random()*10); myarr[0]=num; while(myarr.length<10) { num = Math.floor(Math.random()*10); for(j=0;j<myarr.length;j++) { if(num==myarr[j]) { break; } } if(j==myarr.length) { myarr[j]=num; } } document.write(myarr.length+"</br>"); for (var k =0; k < myarr.length; k++) { document.write(myarr[k]+"</br>"); } </script> </head> <body> </body> </html>
如上是我的代码