使用prototype自定义数组方法

来源:互联网 发布:手机底部导航栏源码 编辑:程序博客网 时间:2024/05/16 09:44

题目

如何实现下列代码:[1,2,3,4,5].duplicator(); // [1,2,3,4,5,1,2,3,4,5]

解决方法

使用array的prototype属性,自定义duplicator()方法,js代码如下:

<!DOCTYPE html><html lang="en"><head>  <meta charset="UTF-8">  <title>Document</title>  <style></style>  <script src="http://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js" type="text/javascript"></script></head><body> <script>  Array.prototype.duplicator = function() {    let s = this.concat(this)    return s  }  let t = [1,2,3,4,5].duplicator()  console.log(t)</script></body></html>

在控制台显示效果如下:

这里写图片描述

注意点

在书写这段代码时Array.prototype.duplicator注意不要添加任何括号,function 内部的this 指代调用这个方法的对象,即array.

阅读全文
0 0
原创粉丝点击