最新通知
js 类型判断
阅读次数:616 最后编辑时间:2022年03月15日

概述

常用数据类型判断。

字符串(String)

typeof

typeof('123') == 'string' //true

数字 (Number)

typeof

typeof(123) == 'number' //true

数组 (Array)

instanceof

let arr = [];
arr instanceof Array; //true

constructor

let arr = [1,3,4];
arr.constructor === Array; //true

Object.prototype.toString.call

let arr = [1,2,3]
Object.prototype.toString.call(arr) === '[object Array]'; //true

Array.isArray

let arr = [1,2,3]
Array.isArray(arr); //true

对象(Object)

typeof

let o = {}
typeof(o) == 'object';  //true;

instanceof

let o = {}
o instanceof Object //true

constructor

var o = {};
o.constructor == Object  //true

Object.prototype.toString.call

let o = {};
Object.prototype.toString.call(o) === '[object Object]'; // true