为数组添加自定义函数,可完成执行[1,2,3,4,5].twoself() 输出新数组[1,2,3,4,5,1,2,3,4,5]

主要是研究如何在数组上添加自定义方法,可以像数组本身提供的splice,push等方法一样直接调用得到想要的结果。

我自定义的方法名是twoself,实现的效果是返回一个新数组,包括该数组的所有元素两次。如[1,2,3,4,5].twoself() 输出[1,2,3,4,5,1,2,3,4,5]。

if (!Array.prototype.twoself){
  Object.defineProperty(Array.prototype,'twoself',{
    value:function(){
      if(this === null){ //判断是否是是null调用的twoself函数
        throw new TypeError('Array.prototype.twoself called on null or undefined')
      }
      var o=Object(this) // 生成了一个数组o  //得到数组的副本
      return [...o,...o];
    }
  })
}

试着用数据去测试;

到此,基本满足需求,虽然总觉得自己的if(this === null)那个判断有点神奇,但是暂时想不到什么时候this会是null,所以还是先留着吧!

参考地址:https://blog.csdn.net/qq_34178990/article/details/81225109 

感谢前辈!

原文地址:https://www.cnblogs.com/toyocc/p/11009341.html