instanceof 运算符
instanceof: 运算符。 用于检测 构造函数的prototype在不在实例对象的原型链中
语法: 实例对象 instanceof 构造函数
返回值:布尔类型值
检测 右边构造函数的prototype 在不在 左边实例对象的原型链中
应用: 某些函数为了限制你的数据类型,在内部需要用instanceof进行判断是否是正确的数据类型
let arr = [10,20,30]
// arr-> Array.prototype -> Object.prototype -> null
console.log( arr instanceof Array )//true
console.log( arr instanceof Object )//true
console.log( arr instanceof String )//false
//封装一个函数,要求这个函数必须要传数组类型、 传其他类型不可以
function fn(arr){
if( arr instanceof Array){
console.log( arr.reverse() )
}else{
console.log('数据类型错误')
}
}
fn( [10,20,30] )
fn( 'abc' )