typeof
:由于js是弱类型的语言,在程序执行中,很容易就出现很多隐性的数据类型的变换,在有些时候,这些隐性的变换很容易就会造成一些不必要的困扰(比如在数据判断的时候使用 “===” 如果数据类型不匹配就是false,或者在和后端交互的时候,提交字符串的时候提交了数字就会造成后端的错误)
它返回字符串
let a = 100
let b = '100'
let c = false
let d = {}
console.log(typeof a, typeof b, typeof c, typeof d);
// 输出为 number string boolean object
typeof运算符用于判断对象的类型,它有以下返回值
"number"、"string"、"boolean"、"object"、"function" "undefined"。
以下可能会在面试题中有,需要注意
console.log(typeof null); // object
// null 并不是空值这么简单的意思,它的实际含义是空指针.
instanceof
: 用于测定某个实例的构造函数,返回布尔值,说得通俗一些,这个方法就是找爸爸
function App(name, uid) {
this.name = name
this.uid = uid
}
let a = new App('kaiqisan', 10001)
console.log(a instanceof App) // true
如果有继承关系,这个方法同样适用,这个方法可以在继承关系中用来判断一个实例是否属于它的父类型。
class App {
constructor(name, uid) {
this._name = name
this._uid = uid
}
}
class Tencent extends App {
constructor() {
super()
}
}
let a = new Tencent('kaiqisan', 10001)
console.log(a instanceof App) // true
PS:以下为面试题常出
console.log(Array instanceof Object); // true
console.log(Function instanceof Object);//true
// 因为函数,数组本质就是对象
console.log(Object instanceof Object);//true
console.log(Function instanceof Function);//true
// 建议查看js的原型链
总结
面试题高频方法 + 测试常用方法
instanceof 在java比较多