JS中类型判断简要概述总结

89 阅读1分钟

 该篇包含typeof、instanceof、Array.isArray()、Object.prototype.toString.call()

1.typeof用于获取变量的数据类型

typeof "Hello World"; // "string"
typeof 123; // "number"
typeof true; // "boolean"
typeof undefined; // "undefined"
typeof null; // "object" (注意:null是typeof操作符的一个例外)
typeof [1, 2, 3]; // "object" (数组也是对象)
typeof {name: "John"}; // "object"
typeof function() {}; // "function"

2.instanceof用于判断一个对象是否是某个构造函数的实例

var arr = [1, 2, 3];
arr instanceof Array; // true
var obj = new Object();
obj instanceof Object; // true

3.Array.isArray()用于判断一个变量是否是数组

Array.isArray([1, 2, 3]); // true
Array.isArray({}); // false

4.Object.prototype.toString.call()可以判断几乎所有类型的值,了解即可,应付面试

Object.prototype.toString.call("Hello World"); // [object String]
Object.prototype.toString.call(123); // [object Number]
Object.prototype.toString.call(true); // [object Boolean]
Object.prototype.toString.call(null); // [object Null]
Object.prototype.toString.call(undefined); // [object Undefined]
Object.prototype.toString.call([1, 2, 3]); // [object Array]
Object.prototype.toString.call(function() {}); // [object Function]