前端面试题之---Object.defineProperty(1)

码字不易,有帮助的同学希望能关注一下我的微信公众号:Code程序人生,感谢!

今天给大家分享几道关于Object.defineProperty的面试题。
Object.defineProperty是前端非常重要的知识点。Vue中核心的双向数据绑定就是通过Object.defineProperty实现的。Object.defineProperty在框架中的应用非常广泛。

if(a === 1 && a ===2 && a ===3){
    
    
    console.log('You win!!!!');
}
如何进入if语句?

这是一道阿里的前端面试题,问题是如何进入题目中的if语句a既等于1,又等于2,也等于3。按照常规的办法,肯定是无法实现的。 这时候就需要用到Object.defineProperty了。

var _default = 0;
Object.defineProperty(window,'a',{
    
    
    get(){
    
    
        return ++_default;
    }
})
if(a === 1 && a ===2 && a ===3){
    
    
    console.log('You win!!!!');
}

在这里插入图片描述
2.

a = 'Object';
console.log(a);
a = 'Array';
console.log(a);
a = '123';
console.log(a);
  
/**
 * {
 *  type:'Object',
 *  length:6
 * }
 * {
 *  type:'Array',
 *  length:5
 * }
 *
 *  TypeError: This type is invalid
*/

题目要求:当a='Object’的时候console.log(a)需要输出的内容是注释的第一个对象a='Array’时,输出的是注释的第二个对象,当a=其它值得时候,输出TypeError: This type is invalid
依然是使用Object.defineProperty解决。

   var _default = null;

   Object.defineProperty(window,'a',{
    
    
       get(){
    
    
           return _default;
       },
       set(newVal){
    
    
        switch(newVal){
    
    
            case 'Object':
            case 'Array':
                _default = {
    
    
                    type:newVal,
                    length:newVal.length
                }
                break;
            default:
                throw new TypeError('This type is invalid');
        }
       }
   })
    a = 'Object';
    console.log(a);
    a = 'Array';
    console.log(a);
    a = '123';
    console.log(a);

在这里插入图片描述
3.

console.log(_+_+_+_); //abcde ....z

console.log里的每个_都代表一个字母,从a开始,_和_相加就继续输出下一个字母。比如题目中的四个_相加,输出的内容就是abcd
仍然使用Object.defineProperty

Object.defineProperty(window,'_',{
    
    
    get(){
    
       
        this._c = this._c || 'a'.charCodeAt(0);
        var _ch = String.fromCharCode(this._c);

        if(this._c >= 'a'.charCodeAt(0) + 26) return;
        this._c ++;

        return _ch;
    }
})

console.log(_ + _ + _ + _);

在这里插入图片描述

以上三个题目,可能通过其它的办法也能完成实际的效果,但是面试官想考察的知识点只是对于Object.defineProperty。下次再看到类似的题目,首先往这方面靠。

今天就给大家分享三个题目,后续会持续更新。


有微信小程序课设、毕设需求联系个人QQ:505417246

关注下面微信公众号,可以领取微信小程序、Vue、TypeScript、前端、uni-app、全栈、Nodejs、Python等实战学习资料
最新最全的前端知识总结和项目源码都会第一时间发布到微信公众号,请大家多多关注,谢谢!

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/m0_46171043/article/details/113044999