1. js判断数据类型有哪些,怎样判断数据类型
(1)数据类型有:undefined、null、Boolean、Number、String、Object、BigInt、Symbol
(2)判断类型的方法(这里加了上数组和函数)
① typeof ,缺点:null 和 数组 在typeof 中判断为'object'
typeof undefined === 'undefined'
typeof null === 'object'
typeof true === 'boolean'
typeof 22 == 'number'
typeof 'abc' === 'string'
typeof Symbol() === 'symbol'
// 判断特殊
typeof {} === 'object'
typeof [] === 'object'
// function 也能通过typeof 判断
typeof function a() {} === 'function'
② Object.prototype.toString.call() ,这个方法能判断所有类型,所以比较常用
Object.prototype.toString.call(undefined) === '[object Undefined]'
Object.prototype.toString.call(null) === '[object Null]'
Object.prototype.toString.call(true) === '[object Boolean]'
Object.prototype.toString.call(123) === '[object Number]'
Object.prototype.toString.call('abc') === '[object String]'
Object.prototype.toString.call(Symbol()) === '[object Symbol]'
// 非基础数据类型
Object.prototype.toString.call([1,2,3]) === '[object Array]'
Object.prototype.toString.call(function a(){}) === '[object Function]'
2. 实现一个bind函数
Function.prototype.newBind = function(context) {
var arg = Array.prototype.slice.call(arguments,1)
const me = this
return function (newArg) {
arg = arg.concat(Array.prototype.slice.call(newArg));
me.apply(context, arguments)
}
}