今天在刷题的时候遇到了setTimeOut,发现了被忽略的第三个参数。html
修改如下 print 函数,使之输出 0 到 99,或者 99 到 0git
要求:github
一、只能修改 setTimeout 到 Math.floor(Math.random() * 1000 的代码bash
二、不能修改 Math.floor(Math.random() * 1000app
三、不能使用全局变量dom
function print(n) {
setTimeout(() => {
console.log(n);
}, Math.floor(Math.random() * 1000));
}
for (var i = 0; i < 100; i++) {
print(i);
}
复制代码
参看各位大神的解法,主要有两种解法:函数
【解法一】ui
利用settimeout 接受多个参数的方法,将Math.floor(Math.random() * 1000)做为第三个参数,第二参数可设为任意值。this
function print(n) {
setTimeout(() => {
console.log(n);
}, 1, Math.floor(Math.random() * 1000));
}
for (var i = 0; i < 100; i++) {
print(i);
}
复制代码
题目中运用到了第三个参数:第三个参数是给setTimeout第一个函数的参数。 settimeout能够传递多个参数,第三个以后的参数均可以做为第一个函数的参数。spa
【解法二】
settimeout第一个参数能够是当即执行或者一个执行函数。
//当即执行函数
function print(n) {
setTimeout((() => {
console.log(n);
})(), Math.floor(Math.random() * 1000));
}
复制代码
function print(n) {
setTimeout(console.log(n), Math.floor(Math.random() * 1000));
}
复制代码
向settimeout传递函数时要注意this的指向:
题目解析:向setTimeout() 传递一个函数时,该函数中的this指向跟你的指望可能不一样,当前这些代码中包含的 this 关键字在非严格模式会指向window对象,严格模式下为undefined。此时能够借助call或apply去改变this指向,便可顺序打印出0到99(或倒序99到0)
function print(n) {
setTimeout((() => {
// console.log(this.i); // 若是不借助call会打印出100次全局变量i,值都为100
console.log(n); // 顺序打印出0~99(100个)
console.log(99 - n); // 倒序打印出99~0(100个)
}).call(null, n), Math.floor(Math.random() * 1000));
}
for (var i = 0; i < 100; i++) {
// console.log(i) // 0~99
print(i);
}
console.log(i) // 注意:此时i在全局window里可访问到,值为100
复制代码