js校验数据类型
typeof 运算符返回变量或表达式的类型
console.log(typeof 1); // number
console.log(typeof "string"); // string
console.log(typeof false); // boolean
console.log(typeof NaN); // number
console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof new Object()); // object
console.log(typeof new Array()); // object
console.log(typeof [1,2]); // object
console.log(typeof function(){}); // function
console.log(typeof new Date()); // object
constructor 属性返回所有 JavaScript 变量的构造器函数。可以区分数组,对象,Date, 函数。但是null,undefined会报错。
console.log("Bill".constructor ); // 返回 [Function: String]
console.log((3.14).constructor ); // 返回 [Function: Number]
console.log(false.constructor ); // 返回 [Function: Boolean]
console.log([1,2,3,4].constructor ); // 返回 [Function: Array]
console.log({name:'Bill', age:62}.constructor ); // 返回[Function: Object]
console.log(new Date().constructor ); // 返回 [Function: Date]
console.log(function () {}.constructor ); // 返回 [Function: Function]
console.log(null.constructor ); // 报错
console.log(undefined.constructor ); // 报错
Object.prototype.toString 方法返回一个表示该对象的字符串
const getType = (obj) => {
return Object.prototype.toString.call(obj).slice(8, -1)
}
console.log(getType(1)); // Number
console.log(getType(() => { })) // Function
console.log(getType(undefined)) // Undefinde
console.log(getType(null)) // Null
console.log(getType('1234')) // String
console.log(getType(false)) // Boolean
console.log(getType(new Date())) // Date
console.log(getType(NaN)) // Number
console.log(getType(new Array)) // Array