typeof 、 instanceof、获取数据类型toString

255 阅读2分钟

一、typeof

作用: 检测简单数据类型的类型,返回一个字符串(除函数外所有的引用类型都会被判定为object)

语法: typeof 操作数

先看几个特殊的,我会在答案处一一解答(答案在下面)
1、console.log(typeof null);
2、console.log(typeof undefined);
3、console.log(typeof 函数名字);
4、console.log(typeof NaN);
5、console.log(typeof console.log);
6、console.log(typeof 100 + 1)
7、console.log(typeof (100 + 1))
8、console.log(typeof typeof 100)
再看几个最基础的
console.log(typeof 100) // 'number'
console.log(typeof '100') // 'string'
console.log(typeof true) // 'boolean'
console.log(typeof abc) // 'undefined'
console.log(typeof {age:100}) // 'object'
console.log(typeof function(){}) // 'function' (函数是一等公民)

答案:

1、'object'(这是在JavaScript初版就流传下来的bug,后面由于修改会造成大量的兼容问题就一直没有被修复...);

2、'undefined';

3、'function'(函数是一等公民);

4、'number'(NaN是非数字,那么非数字也归为数字);

5、'function'(console.log是个函数,因为它要用有括号);

6、'number1'(typeof 100 + 1 其中typeof的优先级比 + 号高,typeof 100 === 'number' 所以结果为'number1');

7、'number';

8、'string'(typeof 的结果是个字符串)

扩展:

题目:let arr = [1,2,3.3,4,5,6,'end']

问题:1、每位数字项元素 + 1,返回一个新的数组; 2、求所有数字项元素的累积

let arr = [1,2,3.3,4,5,6,'end']
let num = 0
let arrNew = arr.map(p => {
    if (typeof p === 'number') {
        num += p
        return p + 1
    } else {
        return p
    }
})
console.log(arrNew,num)

二、instanceof

作用: 用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置

语法: 对象 instanceof 构造函数 // ps:[] instanceof Array

// [] ==> Array.prototype ==> Object.prototype ==> null;
console.log([] instanceof Array); // true
console.log([] instanceof Object); // true
console.log([] instanceof Object.prototype); // 语法错误,instanceof右边是个构造函数
// Array ==> Function.prototype ==> Object.prototype == null
console.log(Array instanceof Function) // true

大家想要更好的了解instanceof一定要对原型以及原型链有一些认知,附上原型链的链接,大家可以学习 juejin.cn/post/684490…

三、获取数据类型(toSting)

我们可以使用toString来获取准确的引用类型:

function getType(target) {
    return Object.prototype.toSting.call(target)
}
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(123) // "[object Number]"
Object.prototype.toString.call('123') // "[object String]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(Symbol()) // "[object Symbol]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call(function() {}) // "[object Function]"
Object.prototype.toString.call([]) // "[object Array]"
Object.prototype.toString.call(new Error()) // "[object Error]"
Object.prototype.toString.call(new RegExp()) // "[object RegExp]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call(JSON) // "[object JSON]"
Object.prototype.toString.call(window) // "[object global]"