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         }

 

 

posted @ 2022-03-28 12:17  编程路上的小张  阅读(127)  评论(0)    收藏  举报