共计 1987 个字符,预计需要花费 5 分钟才能阅读完成。
平时业务代码写多了,学习又懈怠,对 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
正文完
发表至: javascript
2019-07-12