笔记-js判断变量类型

平时业务代码写多了,学习又懈怠,对js的基本功能都不太熟悉了,面试答不上来,哭唧唧

1.使用typeof

判断的是基本数据类型。

{} object
[] object
function(){} function
'1' string
null object
undefined/未定义变量 undefined
1/NaN number
true boolean
Symbol() symbol

2.使用instanceof操作符

主要基于object类型的判断。

假设基于React.Component创建一个类

class Board extends React.Component {
    //...
    
    render() {
        console.log(this instanceof Board);// true
        console.log(this instanceof React.Component);// true  
        console.log(React.Component.prototype.isPrototypeOf(this));// true
        console.log(this instanceof Object);// true
        console.log(this instanceof Game);// false
    }
    
    //...
}

class Game extends React.Component {
    // ...
}

5个log分别是true true true true false。
基本可以看出instanceof与原型链有关,MDN上的描述是The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.
是否这个构造函数的prototype属性出现在这个对象的原型链中。

如果改动了React.Component.prototype,就会出现

console.log(this instanceof React.Component); // false  

其他🌰

/^\+?(\d*\.?\d{0,2})$/ instanceof RegExp; // true
new Date() instanceof Date; // true

3.使用constructor检测

返回对象相对应的构造函数。

// 基础类型
[].constructor -> [Function: Array]

{}.constructor -> error
let obj = {}
obj.constructor -> [Function: Object]

let bx = 1;
bx.constructor -> [Function: Number]

// 自定义类型
function g() {}
let g1 = new g();
g1.constructor -> node: [Function: g]  chrome console: ƒ g() {}

4.利用Object.prototype.toString方法

ES5

Object.prototype.toString.call(NaN); // [object Number]
Object.prototype.toString.call(1); // [object Number]
Object.prototype.toString.call(false); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call({}); // [object Object]
Object.prototype.toString.call([]); // [object Array]
Object.prototype.toString.call(Symbol()); // [object Symbol]
Object.prototype.toString.call(new Date()); // [object Date]

5.数组的判断 isArray

console.log(Array.isArray([]));// true
console.log(Array.isArray({}));// false
Array.isArray(null); // false

[] instanceof Array; // true
[].constructor === Array; // true
Object.prototype.toString.call([]); // [object Array]
参考博客:https://blog.csdn.net/u010998803/article/details/80732942
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章