likes
comments
collection
share

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

作者站长头像
站长
· 阅读数 15

每日3题

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

function showCase(value){
    switch(value){
        case 'A':
            console.log('case A');
            break;
        case 'B':
            console.log('case B');
            break;
        case undefined:
            console.log('undefined');
            break;
        default:
            console.log('Do not know');
            
    }
}
 
showCase(new String('A'));

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

function f(){}
const a = f.prototype,
      b = Object.getPrototypeOf(f);
 
console.log(a===b);

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

console.log(typeof null)
console.log(null instanceof Object)
公众号【今天也要写bug】更多前端面试题

答案与解析

28

// 答案:Do not know
// 考察基本字符串、字符串对象和 switch
// 字符串字面量是 string 类型
// 字符串对象是 object 类型
// switch 使用严格运算符(===)来进行比较
// 在下面 switch case 没有匹配的 case,因此走的是 default
function showCase(value) {
  switch (value) {
    case "A":
      console.log("case A");
      break;
    case "B":
      console.log("case B");
      break;
    case undefined:
      console.log("undefined");
      break;
    default:
      console.log("Do not know");
  }
}

showCase(new String("A"));

29

// 答案:false
// 考察原型链
// 函数本身也是对象
// 函数作为对象,是new Function 构造函数产生的,所以 f.__proto__ => Function.prototype
// 函数的 f.prototype 则默认是一个空对象,和 f.__proto__ 没有关系
function f() {}
const a = f.prototype,
  b = Object.getPrototypeOf(f);

console.log(a === b);
// Object.getPrototypeOf 方法返回对象的原型对象即 f.__proto__
// f.prototype 不等于 f.__proto__
// 最终输出 false

30

// 答案:object false
// 考察 typeof、instanceof、原型链
console.log(typeof null); // 记住就好了 typeof null 为 object
console.log(null instanceof Object);
// instanceof运算符用于检测构造函数(右边)的 prototype 属性是否出现在实例对象(左边)的原型链上
// null 是原型链的终点,Object.prototype 当然不会出现在 null 的原型链上
转载自:https://segmentfault.com/a/1190000042451547
评论
请登录