每日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]=1console.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