欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数组对象的方法重写

程序员文章站 2022-03-03 22:33:19
...

对数组对象方法的重写练习

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. </head>
  7. <body>
  8. <script>
  9. function Marry(){
  10. this.length=arguments.length;
  11. for (var i=0;i<arguments.length;i++){
  12. this[i]=arguments[i];
  13. }
  14. this.pop=function (){
  15. var popData=this[this.length-1];
  16. delete this[this.length-1];
  17. this.length --;
  18. return popData;
  19. }
  20. this.push = function (){
  21. for (i=0;i<arguments.length;i++){
  22. this[this.length]=arguments[i];
  23. this.length++
  24. }
  25. return this.length;
  26. }
  27. this.shift =function (){
  28. var shiftData=this[0];
  29. delete this[0];
  30. this.length--;
  31. for (var i=0;i<this.length;i++)
  32. {
  33. this[i] = this[i+1];
  34. }
  35. delete this[this.length];
  36. return shiftData;
  37. }
  38. this.unshift = function (){
  39. var sum =this.length +arguments.length;
  40. for (i=sum-1;i>= arguments.length;i--){
  41. this[i]=this[i-arguments.length];
  42. }
  43. for (i=0;i<arguments.length;i++){
  44. this[i] =arguments[i];
  45. this.length++;
  46. }
  47. return this.length
  48. }
  49. this.MtoString = function (){
  50. var result = '';
  51. for (i=0;i<this.length-1;i++)
  52. {
  53. result = result +this[i]+',';
  54. }
  55. result+=this[i];
  56. return result;
  57. }
  58. }
  59. arr=new Marry('zhangsan','lisi','wangwu','maqi');
  60. console.log(arr.length);
  61. console.log(arr);
  62. document.write(arr[0]);
  63. console.log(arr.pop());
  64. console.log(arr.length);
  65. console.log(arr);
  66. console.log(arr.push('tt','wqwd','asdasd'));
  67. console.log(arr.push('yu'));
  68. console.log(arr);
  69. //
  70. console.log(arr);
  71. console.log(arr.shift());
  72. console.log(arr);
  73. console.log(arr.unshift('tuyi','nmb','hujing'));
  74. console.log(arr);
  75. console.log(arr.MtoString());
  76. </script>
  77. </body>
  78. </html>