serendipityApe / javascriptPromotion

资深前端必备的编码问题
3 stars 0 forks source link

查看对象类型 #22

Open serendipityApe opened 2 years ago

serendipityApe commented 2 years ago

题目 Detect data type in JavaScript

例子

这是个简单的问题。

对于JavaScript中的所有基础数据类型,请实现一个方法进行检测。

除了基础数据类型之外,你的方法需要额外支持常见的类型包括Array、ArrayBuffer、Map、 Set、Date 和 Function。

该题目的目标并不是想要你列举出所有数据类型,而是想要你证明你能解决该类型的问题。

类型名请返回小写。

detectType(1) // 'number'
detectType(new Map()) // 'map'
detectType([]) // 'array'
detectType(null) // 'null'

// judge的时候会有更多

答案

function detectType(data){ if(data instanceof FileReader) return 'object'; return Object.prototype.toString.call(data).replace(/[|]/g,'').split(' ')[1].toLowerCase(); }

>补充 js类型判断

**instanceof** 
 > target instanceof constructor,检测constructor的prototype是否在target的原型链上,只可以检测引用类型,如Array,Object,Function,Map等

    let a=[0,1];
    a instanceof Array  //true
  **constructor**
> 通过target的constructor属性判断,null和undefined无原型链,不能通过该方法判断。同时constructor可以被更改,所以此方法并不安全

let a=100; console.log(a.constructor === Number) //true //可以被更改 a.proto.constructor=String;
console.log(a.constructor === String) //true


**Object.prototype.toString.call(target)**
>本题所用方法,推荐使用

[更多详细信息请点此](https://www.wolai.com/rVzd1CzGbWxPB4yEck9P7y?theme=light)