Object.prototype.toString.call()
为什么要使用 Object.prototype.toString.call()
传统情况下我们需要判断一个变量的数据类型会使用 typeof
进行判断。但是typeof判断有局限性,因为它只能判断 Number
、String
、Undefined
、Boolean
、Object
这五种数据类型。对于数组、对象以及null来说使用 typeof
都会统一返回为 Object
。它只能判断基本数据类型。
let n1;
let n2 = 123;
let n3 = '我是字符串';
let n4 = [];
let n5 = {};
let n6 = null;
let n7 = function(){};
console.log(typeof n1); //undefined
console.log(typeof n2); //number
console.log(typeof n3); //string
console.log(typeof n4); //object
console.log(typeof n5); //object
console.log(typeof n6); //object
console.log(typeof n7); //function
所以我们就需要使用 Object.prototype.toString.call()
进行判断
// 使用Object.prototype.toString.call()来判断数据类型
let judge1 = Object.prototype.toString.call(); //[object Undefined]
let judge2 = Object.prototype.toString.call(123); //[object Number]
let judge3 = Object.prototype.toString.call('我是字符串'); //[object String]
let judge4 = Object.prototype.toString.call([]); //[object Array]
let judge5 = Object.prototype.toString.call({}); //[object Object]
let judge6 = Object.prototype.toString.call(function () { }); //[object Function]
let judge7 = Object.prototype.toString.call(null); //[object Null]
举个栗子
判断n的值是什么数据类型
let n = function () { }
if (Object.prototype.toString.call(n) === '[object String]') {
console.log(n + ': 他是个字符串');
} else if (Object.prototype.toString.call(n) === '[object Array]') {
console.log(n + ': 他是个数组');
} else if (Object.prototype.toString.call(n) === '[object Function]') {
console.log(n + ': 他是个函数'); //输出这个
} else if (Object.prototype.toString.call(n) === '[object Object]') {
console.log(n + ': 他是个对象');
}
链接: http://www.bylemon.cn
描述: 嘿,我在这~
头像: http://www.bylemon.cn/favicon.ico已经添加贵站,望互关~