instanceof运算符的原理:检测 右边的 构造函数的prototype,在不在,左边的实例对象的原型链中。
instanceof的应用:限制函数参数的数据类型。
// arr -> Array.prototype -> Object.prototype -> null
let arr = [10,20,30]
console.log( arr instanceof Array )//true
console.log( arr instanceof Object )//true
console.log( arr instanceof String )//false
//instanceof一般用于限制函数的参数数据类型
function reverseArr(arr){
//如果用户传数组,就翻转。 不是数组,原路返回
if( arr instanceof Array ){
return arr.reverse()
}else{
return arr
}
}
let res = reverseArr([10,20,30])
let res1 = reverseArr('123')
console.log(res,res1)