zxdfe / FE-Interview

Every step counts
34 stars 1 forks source link

第12题:JS中检测数据类型的方式有哪些? #12

Open zxdfe opened 1 year ago

shuke-zhang commented 1 year ago

完美检测数据类型 :Object.prototype.toString.call() ===> 返回该数据的数据类型 基本数据检测类型: typrof ===> 返回 基本数据类型 引用数据类型: A instanceof B ===> 返回 true false 判断是不是数组,数组专用 Array.isArray( ) ===> 返回 true false

Nan-Ping commented 1 year ago

上面这位同学单词写错了,typeof

shuke-zhang commented 1 year ago

完美检测数据类型 :Object.prototype.toString.call() ===> 返回该数据的数据类型 基本数据检测类型: typeof() ===> 返回 基本数据类型 引用数据类型: A instanceof B ===> 返回 true false 判断是不是数组,数组专用 Array.isArray( ) ===> 返回 true false

rupoly commented 1 year ago

基本数据类型:typeof 引用数据类型:A instanceof B 完美:Object.prototype.toString.call()

WLNCJL commented 1 year ago
1. typeof  检测基本数据类型,返回基本数据类型
2. instanceof  检测引用数据类型,返回true/false
3. Object.prototype.toString.call() 两个都可以检测,返回数据类型
z-forever-y commented 1 year ago
检测基本数据类型:typeof
检测引用数据类型:A instanceOf  B
完美型:Object.prototype.toString.call()
lemon-912 commented 1 year ago

检测基本数据:typeof  返回数据类型
检测引用数据类型:A instanceof B   返回true/false
完美型:Object.prototype.toString.call ()   返回数据类型
Qian-e commented 1 year ago

基本数据类型:typeof 引用数据类型:A instanceof B 既能检测基本数据类型又能检测引用数据类型:Object.prototype.toString.call ()

stevenhuanghr commented 1 year ago
基本数据检测:typeof
应用数据检测:instanceof 返回值是布尔值
精准检测:Object.prototype.toString.cell()
BlueSky-Engineer commented 1 year ago

JS检测数据类型的方式

  1. typeof
  2. instanceof
  3. constructor
  4. Object.prototype.toString.call()
dyxfe commented 1 year ago
1、 typeof
2、 instanceof
3、Object.prototype.toString.call()
CLHaoer commented 1 year ago

js检测数据类型的方式:

//1. typeof() / typeof 被检测的数据:
typeof 37 ===> 'number';
typeof '' ===> 'string';
typeof Boolean(1) ===> 'boolean';
typeof null ===> "object";
//2. 对象 instanceof 构造函数:instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上
function C(){}
function D(){}
const o = new C();
o instanceof C; // true,因为 Object.getPrototypeOf(o) === C.prototype
o instanceof D; // false
//3. Object.prototype.toString.call()
let a = "b" 
let b = true 
let c = 123 
Object.prototype.toString.call(a) ===>  '[object String]'
Object.prototype.toString.call(b) ===>  '[object Boolean]'
Object.prototype.toString.call(c) ===>   '[object Number]'
YangYi-Mo commented 1 year ago

● typeof:检测简单数据类型,null(特殊,结果为Object),不能区分数组 ● A instanceof B 检测复杂数据类型,对于基本数据类型无效 ● constructor 判断当前的实例的constructor的属性值是不是预估的类 ● Object.proprtype.toString.call(),完美的数据检测方法

CDwenhuohuo commented 1 year ago

typeof 适用于检测基本数据类型,注意:null检测为object A instanceof B 返回值是布尔值,用于检查复杂数据类型 Object.prototype.toString.call( ) 检测数据类型最完美的方式