js中检测数据类型的方式

js中的数据类型有:

基本数据类型: Undefined, Null, Boolean, Number, String
复杂数据类型: Object

1. typeof 操作符的用法

  • 缺点:检测引用类型的值时,用处不大;
  • 对于对象,null类型的数据均返回object,无法具体区分,
console.log(typeof 'hello');    //string
console.log(typeof 123);      //number
console.log(typeof false);  //boolean
console.log(typeof undefined);  //undefined
console.log(typeof null);   //object
console.log(typeof {name:'张三'});  //object
console.log(typeof function f(){}); //function
console.log(typeof [1,2,3]);  //object

2. instanceof操作符的用法,判断变量是否是给定引用类型的实例,如果是返回true

let s = new String('hello')
console.log(s);
console.log(s instanceof String); //true
console.log('hello' instanceof String); //false
console.log([1,2,3] instanceof Array);    //true
console.log({name:'张三'} instanceof Object);   //true
console.log(/.ab/g instanceof RegExp);   //true

3. Object.prototype.toString.call(value)

// 3.1.判断基本类型:
console.log( Object.prototype.toString.call(null));   //[object Null]
console.log( Object.prototype.toString.call(undefined));  //[object Undefined]
console.log( Object.prototype.toString.call('hello'));    // [object String]
console.log( Object.prototype.toString.call(123));  //[object Number]
console.log( Object.prototype.toString.call(false));  //[object Boolean]

// 3.2.判断原生引用类型:
// 函数类型
console.log(Object.prototype.toString.call(function f(){}));  //[object Function]
// 日期类型
console.log(Object.prototype.toString.call(new Date()));    //[object Date]
// 数组类型
console.log(Object.prototype.toString.call([1,2,3]));   //[object Array]
// 正则表达式
console.log(Object.prototype.toString.call(new RegExp('ab','i')));  //[object RegExp]
// Set
console.log(Object.prototype.toString.call(new Set()));  //[o// Map
console.log(Object.prototype.toString.call(new Map()));  //[object Map]
    
// 3.3自定义类型
function Person(name, age) {
    this.name = name;
    this.age = age;
}
var person = new Person("张三", 18);
console.log(Object.prototype.toString.call(person)) ;  // [object Object]
// 很明显这种方法不能准确判断person是Person类的实例,而只能用instanceof 操作符来进行判断,如下所示:
console.log(person instanceof Person);  //true

你可能感兴趣的:(JavaScript)