1. 程式人生 > 其它 >JavaScript每日一題

JavaScript每日一題

 修改下面程式碼,順序輸出0-99

            要求:

                1、只能修改setTimeout 到 Math.floor(Math.random())

                2、不能修改Math.floor(Math.random() * 1000)

                3、不能使用全域性變數

 


1         function print(n) {
2             setTimeout(() => {
3                     console.log(n);
4             }, Math.floor(Math.random() * 1000));
5 } 6 for (var i = 0; i < 100; i++) { 7 print(i); 8 }

 方法一 將setTimeout函式第一個函式引數改變為立即執行函式

1         function print(n) {
2             setTimeout((() => {
3                     console.log(n);
4                     return () => {};
5             })(), Math.floor(Math.random() * 1000));
6 } 7 for (var i = 0; i < 100; i++) { 8 print(i); 9 }

方法二: 將setTimeout函式第二個隨機時間的引數變為第三個引數,這樣就不控制函式等待時間

1         function print(n) {
2             setTimeout((() => {
3                     console.log(n);
4                     return () => {};
5             })(),10, Math.floor(Math.random() * 1000));
6 } 7 for (var i = 0; i < 100; i++) { 8 print(i); 9 }