前端面试

81 阅读1分钟

JS面试

  1. 判断对象为空有哪些方法
  • Object.keys():返回对象自身所有可枚举属性,不包含原型链上的属性,返回的是一个数组
  • JSON.stringify():将对象转换位json字符串,通过判读是否为空对象
  • Object.getOwnPropertyNames():方法返回一个由指定对象的所有自身属性的属性名(包括不可枚举属性但不包括(Symbol)值作为名称的属性)组成的数组
  • for...in:返回对象所有可枚举属性,包括原型链上的属性,返回的是一个数组,需要结合hasOwnProperty来使用
let obj={a:1}
//方法1
if(Object.keys(obj).length===0){
  console.log(true)
}

//方法2
if(JSON.stringify(obj)==='{}'){
  console.log(true)
}

//方法3
if(Object.getOwnPropertyNames(obj).length===0){
  console.log(true)
}

//方法4
function isObj(data){
  for(let p in data){
    if(data.hasOwnProperty(p)){
      return false
    }
  }
  return true
}

2.判断对象是否为数组的方面有哪些

  • Array.isArray():
  • instanceof:判断对象是否为数组的实例
  • arr.constructor
  • Object.prototype.toString.call():通过对象原型链上的call方法判断是否为[object Array]
let arr=[]
//方法1
if(Array.isArray(arr)){
  console.log('arr is Array')
}

//方法2
if(arr instanceof Array){
  console.log('arr is Array')
}

//方法3
if(arr.constructor===Array){
  console.log('arr is Array')
}

//方法4
if(Object.prototype.toString.call(arr)==='[object Array]'){
  console.log('arr is Array')
}