美文网首页
Javascript类型判断

Javascript类型判断

作者: 住在醉翁亭边 | 来源:发表于2019-08-08 09:25 被阅读0次

typeof操作符

主要用来检测基本类型。

// 基本类型
let u = undefined;  // Undefined
let n = null;       // Null   
let b = true;       // Boolean
let str = 'string'; // String
let num = 123;      // Number

// 引用类型Object
let arr = [1,2];
let fun = function(){};
let obj = {};

// es6新增类型Symbol
let symbol = Symbol();

console.log( typeof u ); // undefined
console.log( typeof n ); // object
console.log( typeof b ); // boolean
console.log( typeof str ); // string
console.log( typeof num ); // number

console.log( typeof arr ); // object
console.log( typeof fun ); // function
console.log( typeof object ); // object

console.log( typeof symbol); // symbol

总结:

  1. typeof操作符可以用来检测基本类型(除了null)和函数。
  2. typeof操作符对null会返回object。
  3. typeof操作符对函数会返回function。
  4. typeof操作符适合用来检测Undefined、Boolean、String、Number和Function。
  5. typeof操作符可以用检测Symbol类型。

instanceof操作符

主要用来检测引用类型

let obj = {};
let arr = [1,2];
console.log( obj instanceof Object ) // true
console.log( arr instanceof Array ) // true

console.log( symbol instanceof Symbol ) // false

总结:
如果变量是给定的引用类型的实例,则返回true

Object.prototype.toString.call()方法

比较安全可靠的类型检测方法,该方法会拿到变量的构造函数名。
返回的格式是"[object ConstructorName]"

console.log( Object.prototype.toString.call(u) ); // [object Undefined]
console.log( Object.prototype.toString.call(n) ); // [object Null]
console.log( Object.prototype.toString.call(str) ); // [object String]
console.log( Object.prototype.toString.call(num) ); // [object Number]
console.log( Object.prototype.toString.call(b) );// [object Boolean]
console.log( Object.prototype.toString.call(arr) ); // [object Array]
console.log( Object.prototype.toString.call(fun) ); // [object Function]
console.log( Object.prototype.toString.call(obj) );// [object Object]
console.log( Object.prototype.toString.call(symbol) );// [object Symbol]
// 检测自定义构造函数生成的变量
function A(){};
let a = new A();
console.log( Object.prototype.toString.call(a) )// [object Object]

总结:
该方法相对安全可靠,但是无法检测自定义构造函数生成的实例变量。

Jquery的$.type()方法

该方法同typeof一样返回数据类型,但是比typeof操作符更加精确。

console.log( $.type(n) ) // null
console.log( $.type(arr) ) // array
console.log( $.type(fun) ) // function
console.log( $.type(obj) ) // object
console.log( $.type(symbol) ) // symbol

相关文章

网友评论

      本文标题:Javascript类型判断

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