美文网首页
数据类型的判断

数据类型的判断

作者: bryan_liu | 来源:发表于2022-03-28 15:57 被阅读0次

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]"

相关文章

网友评论

      本文标题:数据类型的判断

      本文链接:https://www.haomeiwen.com/subject/spppjrtx.html