前端面试题JavaScript篇——2022-09-16

每日3题

1 以下代码执行后,控制台中的输出内容为?

 // 以下代码执行后,浏览器的控制台中输出的内容是什么
var arr = [0, 1, 2];
arr[10] = 10;
var newArr = arr.filter((x) => x === undefined);

console.log(newArr);

2 以下代码执行后,控制台中的输出内容为?

 // 以下代码执行后,控制台中输出的内容是什么
const obj = {
2: 3,
3: 4,
length: 2,
push: Array.prototype.push,
};
obj.push(1);
console.log(obj);

3 以下代码执行后,控制台中的输出内容为?

 // 以下代码执行后,控制台中输出的内容是什么
let x;
try {
throw new Error();
} catch (x) {
x = 1;
console.log(x);
}

console.log(x);
  • 公众号【今天也要写bug】更多前端面试题

答案及解析

1

 // 答案:[]
// 考察 filter 方法
var arr = [0, 1, 2];
arr[10] = 10;
var newArr = arr.filter((x) => x === undefined);
// 传入 filter 方法的函数,只会在已经赋值的索引上被调用,对于那些已经被删除或者从未被赋值的索引不会被调用。
// 所以最终没有值通过测试
console.log(newArr);

2

 // 答案:{ '2': 1, '3': 4, length: 3, push: [Function: push] }
// 考察 push 方法
// push 方法可以应用在类似数组的对象上
// push 方法根据 length 属性来决定从哪里开始插入给定的值
const obj = {
2: 3,
3: 4,
length: 2,
push: Array.prototype.push,
};
obj.push(1); // obj.length=2,所以 push 插入到索引 2 处,即 obj[2]=1
console.log(obj);

3

 // 答案:1 undefined
// 考察 catch 和作用域
// catch块指定一个标识符(在下面为x),该标识符保存由throw语句指定的值。
// catch块是唯一的,因为当输入catch块时,JavaScript 会创建此标识符,并将其添加到当前作用域;
// 标识符仅在catch块执行时存在;catch块执行完成后,标识符不再可用。
let x;
try {
throw new Error();
} catch (x) {
// x 仅在 catch 块中可用
x = 1;
console.log(x); // 输出 1
}

console.log(x); // x 从未赋值,输出 undefined

标签: Javascript

添加新评论