js类型判断
typeOf
- typeof操作符一般用来检测基本数据类型,返回以下某个字符串:'undefined', 'boolean', 'number', 'string', 'object', 'function'。
- null, Array, Date, RegExp, Object都返回'object'。
- function虽然也是对象的一种,但是函数具有某些特殊属性,因此通过typeof来区分函数和其他对象是有必要的
js
typeof(99)instabceof
instanceof 运算符用于检测构造函数的 prototype 属性是否出现在某个实例对象的原型链上。
js
class Lei {
}
let temp = new Lei()
console.log(temp instanceof Lei, temp.__proto__ === Lei.prototype)字符串
js
let str = 'str'
let str2 = String('str')
let str3 = new String('str')
typeof(str) // string
typeof(str2) // string
typeof(str3) // Object
str.__proto // String
str2.__proto // String
str3.__proto // String
let str4 = str3 + ''
typeof(str4) // string
str4.__proto // String数组判断
- instanceof arr instanceof Array
- proto arr._proto === Array.prototype
- Object.prototype.toString Object.prototype.tostring.call(arr) === '[objdect Array]'
- Array.isArray() Array.isArray(arr)
- constructor arr.constractor === Array
对象判断
- typeof 只能判断基本类型
- instanceof obj intancepof Object
- constructor obj.contractor === Object
- Object.prototype.toString Object.prototype.tostring.call(obj) === '[objdect Object]'
JStar