面试题

一.JavaScript

1. foreach 如何跳出循环?

例子

1
2
3
4
5
6
7
8
9
10
11
12
try {
const arr = [1, 2, 3, 4, 5, 6];
arr.forEach((item) => {
if (item === 4) {
throw new Error("error");
}
console.log(item);
});
} catch (e) {
if (e.message != "error") throw e;
}
console.log(100); // 结果 1,2,3,100

2.箭头函数的 this 指向?为什么箭头函数没有自己的 this?

箭头函数的 this 指向是上级作用域的 this,如果上级也没有 this,会继续往上找。

箭头函数没有 prototype(原型),所有箭头函数本身没有 this。