1.使用 typeof 操作符 ,返回传入对象对应的类型
function judgeType1 (obj) {
if (obj === null) return "null";
if (Array.isArray(obj)) return "array";
return (typeof obj);
}
注:函数返回一个字符串,表示传入参数所对应的类型。( 如:传入1,返回 "number" ; 传入"love",返回 "string" ; 传入 [1,255,66] ,返回 "array" 等 )
(1) typeof 123 === "number"
(2) typeof ''fff" === "string"
(3) typeof true === "boolean"
(4) typeof undefined === "undefined"
(5) typeof null === "object"
(6) typeof [1,3,45] === "object"
(7) typeof {name:"34"} === "object"
(8) typeof funtion () {} === "function"
2.使用 instanceof 操作符,返回传入对象对应的类型
function judgeType2 (obj) {
if (obj === null) return "null";
if (obj instanceof Array) return "array";
return (typeof obj);
}
3.使用 Object.prototype.toString, 返回传入对象对应的类型
function judgeType2 (obj) {
return Object.prototype.toString.call(obj).slice(8,-1).toLowerCase();
}
(1) Object.prototype.toString.call(undefined) === "[object Undefined]"
(2) Object.prototype.toString.call(null) === "[object Null]"
(3) Object.prototype.toString.call(123) === "[object Number]"
(4) Object.prototype.toString.call('fff') === "[object String]"
(5) Object.prototype.toString.call(true) === "[object Boolean]"
(6) Object.prototype.toString.call([12,45]) === "[object Array]"
(7) Object.prototype.toString.call({age:12}) === "[object Object]"
(8) Object.prototype.toString.call(function(){}) === "[object Function]"
(9) Object.prototype.toString.call(Math) === "[object Math]"
Object.prototype.toString.call(value)
数值: [object Number]
字符串: [object String]
布尔值: [object Boolean]
undefined: [object Undefined]
null: [object Null]
数组: [object Array]
arguments对象: [object Arguments]
函数: [object Function]
Error对象: [object Error]
Date对象: [object Date]
RegExp对象: [object RegExp]
其他对象: [object Object]
4.使用 Object.prototype.toString 和 正则表达式组匹配
function getType (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*)\]/)[1].toLowerCase();
}
注意:
1 使用 Object.prototype.toString.call(o) 把传入参数转化为了其对应的类型字符串
2 使用字符串的 match 方法以及 正则表达式的组匹配 取得了传入参数对应的类型. (返回的是正则表达式中小括号里匹配的内容)
getType({}); // "object"
getType([]); // "array"
getType(5); // "number"
getType(null); // "null"
getType(); // "undefined"
getType(/abcd/); // "regex"
getType(new Date()); //"date"
const myDate = new Date();
Object.prototype.toString.call(myDate); // [object Date]
myDate[Symbol.toStringTag] = 'myDate';
Object.prototype.toString.call(myDate); // [object myDate]
Date.prototype[Symbol.toStringTag] = 'prototype polluted';
Object.prototype.toString.call(new Date()); // [object prototype polluted]
网友评论