forEach面题及this指针
Opened this issue · 0 comments
machao07 commented
1、forEach()中的this
- 第一个参数是回调函数
- 第二个参数用来绑定回调函数的this关键字,不传默认undefined,指向全局(window)
var obj = {
name: '哈哈',
times: [1,2,3],
fn(){
console.log(this)
}
}
obj.times.forEach(obj.fn) // 指向Window
obj.times.forEach(obj.fn, obj) // 指向obj {name: '哈哈', times: Array(3), fn: ƒ}
obj.times.forEach(obj.fn, obj.times) // 指向times [1, 2, 3]
obj.times.forEach(obj.fn, 0) // 指向Number类型对象 Number {0}
2、forEach 与 for...of 区别
- forEach不可以中断循环,默认请求并行发起 同时
- for循环是可以中断循环(利用break语句或return语句)
例题:输出以下代码运行结果,为什么?如果希望每隔 1s 输出一个结果,应该如何改造?注意不可改动 square 方法
const list = [1, 2, 3]
const square = num => {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(num * num)
}, 1000)
})
}
function test() {
list.forEach(async x=> {
const res = await square(x)
console.log(res)
})
}
test() // 1 4 9 同时输出
forEach 改成 for…of
async function test() {
for (let x of list) {
const res = await square(x)
console.log(res) // 1 4 9 每隔一秒输出一个
}
}
forEach 跳出循环方法 try…catch...
try {
var arr = [1, 2, 3, 4];
arr.forEach(function (item, index) {
//跳出条件
if (item === 3) {
throw new Error("LoopTerminates");
}
//do something
console.log(item);
});
} catch (e) {
if (e.message !== "LoopTerminates") throw e;
}