typeof用法&&重写typeof

用法:

  1. 对于原始类型来说,除了null,使用typeof都可以显示正确的类型
typeof 1;	//'number'
typeof '1';		//'string'
typeof undefined;	//'undefined'
typeof true;	//'boolean'
typeof Symbol();	//'symbol'

null

typeof null; //'object'
  1. 对于引用数据类型,除了函数之外,都会显示’object’
typeof [];	//'object'
typeof {
    
    };	//'object'
typeof console.log;	//'function'

重写typeof()

第一种

function _typeof(value){
    
    
	let type = Object.prototype.toString.call(value).split('')[-1].split(']')[0].toLowerCase()
	if(type == 'null' || type == 'function')	return 'object'
	return type
}

测试代码:

console.log(null, _typeof(null))
console.log(undefined, _typeof(undefined))
console.log({
    
    }, _typeof({
    
    }))
console.log([], _typeof([]))
console.log(20, _typeof(20))
console.log('123', _typeof('123'))
console.log(new Date(), _typeof(new Date()))
console.log(new Function(), _typeof(new Function()))
console.log(new RegExp(), _typeof(new RegExp()))
console.log(Symbol(), _typeof(Symbol()))

第二种:暂时还没想到

猜你喜欢

转载自blog.csdn.net/qq_45465526/article/details/121301516