Skip to content

Latest commit

 

History

History
33 lines (24 loc) · 780 Bytes

Js数据类型之检测.md

File metadata and controls

33 lines (24 loc) · 780 Bytes

Js数据类型之检测

1、typeof是否能正确判断类型

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

typeof 1 //number
typoof '1' //string
typeof undefined //undefined
typeof true //boolean

但对于引用数据类型,除了函数,都会显示Object

typeof []; //object
typeof null //object

因此采用typeof判断对象的数据类型是不合适的,采用instanceof会更好,instanceof的原理是基于原型链的查询,只要处于原型链中,判断永远为true

const Person = function(){}
const p1 = new Person();
p1 instanceof Person //true

var str1 = 'afa';
str1 instanceof String //false
var str2 = new String('hello world');
str2 instanceof String //true