判断数据类型,
- typeof,能判断基本数据类型和函数,不能判断数组,数组要用其他方式判断
console.log(typeof 'abc') //string
console.log(typeof 1) //number
console.log(typeof {}) //object
console.log(typeof function(){}) //function
console.log(typeof Symbol()) //symbol
console.log(typeof []) //object typeof无法判断数组
console.log([] instanceof Array) //true 判断是否是数组
- 借用Object的toString方法
console.log(Object.prototype.toString.call('a','string')) //[object String]
console.log(Object.prototype.toString.call(type)) //[object Function]
console.log(Object.prototype.toString.call(1)) //[object Number]
console.log(Object.prototype.toString.call({})) //[object Object]
console.log(Object.prototype.toString.call(true)) //[object Boolean]s
console.log(Object.prototype.toString.call([])) //[object Array]
console.log(Object.prototype.toString.call(Symbol())) //[object Symbol]
/**
* 判断数据类型
* @param {*} val 传入的数据
* @param {*} type 传入某个类型'function','number','object','boolean','array','symbol','String' ,返回布尔值
* @returns
*/
function type(val,type) {
var typeStr = Object.prototype.toString.call(val);
typeStr = typeStr.slice(8,-1).toLowerCase()
if(!type) return typeStr
var types = ['function','number','object','boolean','array','symbol','string'];
for(var i=0;i<types.length;i++){
if(types[i] === type.toLowerCase()){
return true
}
}
return false
}
console.log(type('a')) //function
console.log(type(type)) //function
console.log(type(1)) //number
console.log(type({},'object')) //object
console.log(type(true,'string')) //false
console.log(type([],'array')) //true
console.log(type(Symbol(),'symbol')) //true
网友评论