jackieli123723 / jackieli123723.github.io

✅lilidong 个人博客
9 stars 0 forks source link

突发奇想一个思考题实现Array.prototype.first模拟 #74

Open jackieli123723 opened 5 years ago

jackieli123723 commented 5 years ago

突发奇想一个思考题实现Array.prototype.first模拟

要求如下:

[1, 2].first() === 1
[].first() === undefined
[null].first() === null

[undefined].first() === undefined

方法 封装

核心就是重写原型链


Array.prototype.first = function(){
  //var args = [].slice.call(arguments);
  //var args = Array.prototype.slice.call(arguments);
  // if(args.length == 0){
  //   return undefined
  // }  

  let len = this.length
  //let toString = {}.toString
  let toString = Object.prototype.toString
  if(len == 0){
    return undefined
  }

  if(toString.call(this) == '[object Null]'){ //call 里面还可以传 undefined 和this
     return null
  }

  if(toString.call(null) == '[object Undefined]'){ // call 里面还可以传 null 和 this
    return undefined
  }

  //彩蛋 call 中的参数 可变 哈哈 
  //或者下面这个版本
  // if(typeof this === 'undefined'){
  //   return undefined
  // }

  return this[0]

}

console.log([null].first()) //null
console.log([].first()) //undefined
console.log([undefined].first()) //undefined
console.log([1,2,3].first()) //1

codepen在线看源码

jackieli123723 commented 5 years ago

:+1: