• 经典面试题第十更---instanceof与typeof


    前言:
        🤡 作者简介:我是Morning,计算机的打工人,想要翻身做主人 🙈 🙈 🙈
        🏠 个人主页: Morning的主页
        📕系列专栏: 前端面试备战
        📞 如果小编的内容有欠缺或者有改进,请指正拙著。期待与大家的交流
        🔥如果感觉博主的文章还不错的话,👍点赞👍 + 👀关注👀 + 🤏收藏🤏

     

     今天咱们来学习一点简单的,轻松愉快,干货满满⭐⭐⭐

    目录

    面试题

    1.typeof

    2.instanceof

    3.笔试题


    面试题

    typeof能否正确判断类型?instanceof能正确判断数据类型的与原理是什么

    对于原始类型来说,除了null都可以显示正确数据类型。

    instanceof内部机制是通过原型链来判断的,检测实例对象的原型链上是否有构造函数的prototype属性

    1.typeof

    对于原始类型来说,除了null都可以显示正确数据类型(null会显示object类型)

    1. console.log(typeof 1);//number
    2. console.log(typeof 'susu');//string
    3. console.log(typeof true);//boolean
    4. console.log(typeof undefined);//undefined
    5. console.log(typeof Symbol());//symbol
    6. console.log(typeof null);//object

    对于对象来说,除了函数都会显示object(函数、数组都属于对象)

    1. console.log(typeof {a:1});//object
    2. console.log(typeof [1,2,3]);//object
    3. console.log(typeof function(){});//function

    2.instanceof

    可以判断复杂数据类型(obj   arr   function),但是不可以判断基本数据类型(即原始类型)

    1. console.log(1 instanceof Number);//false
    2. console.log({a:1} instanceof Object);//true
    3. console.log([1,2,3] instanceof Array);//true
    4. console.log(function(){} instanceof Function);//true
    5. var Person=function(){}
    6. var person1=new Person()
    7. console.log(person1 instanceof Person);//true
    8. var str='hello susu'
    9. console.log(str instanceof String);//false
    10. var str=new String('hello susu')
    11. console.log(str instanceof String);//true

    3.笔试题

    需求:写一个函数可以返回参数的具体数据类型

    1. function getType(target){
    2. var ty
    3. if(typeof target=='object'){
    4. //此处使用了短路表达式
    5. ty='null' //此行代码必须写在if的第一行。用来判断是否为null
    6. target instanceof Object && (ty='Object')
    7. target instanceof Array && (ty='Array')
    8. }else{
    9. typeof target === 'string' && (ty='string')
    10. typeof target === 'number' && (ty='number')
    11. typeof target === 'boolean' && (ty='boolean')
    12. typeof target === 'undefined' && (ty='undefined')
    13. typeof target === 'function' && (ty='function')
    14. typeof target === 'symbol' && (ty='Symbol')
    15. }
    16. return ty
    17. }
    18. console.log(getType(function fn(){}));
    19. console.log(getType(1));
    20. console.log(getType('sss'));
    21. console.log(getType(undefined));
    22. console.log(getType(true));
    23. console.log(getType([1,2,3]));
    24. console.log(getType({a:1,b:2}));
    25. console.log(getType(Symbol()));
    26. console.log(getType(null));

    a112268dbc2742eaa868ba833051b4b1.png

  • 相关阅读:
    OpenCV | 直线拟合fitline函数(Python)
    06 - ip route和route -n的区别
    (codeforce547)C-Mike and Foam(质因子+容斥原理)
    单/三相dq解耦控制与特定次谐波抑制
    【晨读算法】为什么经常看到使用朴素贝叶斯公式的时候把分母忽略了?
    【数据结构与算法】二叉树的链式访问
    使用JacORB编译idl文件生成依赖的开发jar---Corba北向接口开发001
    【Linux】基础指令(三) —— 收尾篇
    如何在 Keras 中开发具有注意力的编码器-解码器模型
    vuejs开发环境搭建
  • 原文地址:https://blog.csdn.net/m0_72154565/article/details/133740163