数据类型的判断

1.typeof:能判断所有值类型,函数,不能判断、数组、对象进行精确判断;

console.log(typeof undefined); // undefined
console.log(typeof true); // boolean
console.log(typeof 2); // number
console.log(typeof "string"); // string
console.log(typeof Symbol("foo")); // symbol
console.log(typeof 2172141653n); // bigint
console.log(typeof function () {}); // function
// 不能判别
console.log(typeof []); // object
console.log(typeof {}); // object
console.log(typeof null); // object

2.instanceof :判断对象类型,不能判断基本数据类型,内部运行机制是在其原型链上能否找到该类型的原型;

class   Person {}
class Student extends Person 
const obj = new Student 
console.log(obj  instanceof Person) //true
console.log(obj  instanceof Student ) //true
//obj 顺着原型链能找到Student.prototype和Person.prototype,所以都为true

3.Object.prototype.toString.call():所有原始数据类型都能判断;

Object.prototype.toString.call(2) //"[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true); // "[object Boolean]"
Object.prototype.toString.call(undefined); // "[object Undefined]"
Object.prototype.toString.call(null); // "[object Null]"
Object.prototype.toString.call(Math); // "[object Math]"
Object.prototype.toString.call({}); // "[object Object]"
Object.prototype.toString.call([]); // "[object Array]"
Object.prototype.toString.call(function () {}); // "[object Function]"
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容