筆記-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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章