【发布时间】:2021-07-09 02:25:25
【问题描述】:
全部。我是 JS 新手。在这里我遇到了一个JS问题,如下所示:
function print(n) {
setTimeout(() => {
console.log(n);
}, Math.floor(Math.random() * 1000));
}
for (var i = 0; i < 100; i++) {
print(i);
}
要求是:
- 您需要更改程序,使其按顺序打印0-99或99-0;
- 不能使用全局变量;
- 只能更改代码内部的setTimeout;
- 您不能修改
Math.floor(Math.random() * 1000。
在这里我得到了这个问题的一些解决方案,但是有些答案我不明白,所以我希望你们能帮助我为什么这可以工作。我理解第一个,第二个和最后一个的答案,但我不太清楚为什么其余的答案可以工作。尤其是第三个,如果我去掉return ()=>{}的代码,代码还是可以的,但是会报错100Refused to evaluate a string as JavaScript because 'unsafe-eval' is not an allowed source of script in the following Content Security Policy directive: "script-src <URL> <URL> 'self' 'unsafe-inline' https:".。
//1.
function print1(n) {
setTimeout(() => {
console.log(n);
}, 1, Math.floor(Math.random() * 1000));
}
// 2.
function print2(n) {
setTimeout(() => {
console.log(i--);
}, Math.floor(Math.random() * 1000));
}
// 3.
function print3(n) {
setTimeout((() => {
console.log(n)
return () => { }
}).call(n, []), Math.floor(Math.random() * 1000));
}
for (var i = 0; i < 100; i++) {
print(i);
}
//4.
function print4(n) {
setTimeout(() => {
setTimeout(() => {
console.log(n);
}, 1000 * n);
}, Math.floor(Math.random() * 1000));
}
// 5.
function print5(n) {
setTimeout((() => {
console.log(n);
})(), Math.floor(Math.random() * 1000));
}
【问题讨论】:
-
这是一个有趣的问题...从这篇文章中学到了很多
标签: javascript closures settimeout event-loop