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

js对象模拟数组

程序员文章站 2022-03-13 13:58:28
...

排序完了不知道要返回数组还是对象,先这样吧

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>object</title>
  6. </head>
  7. <body>
  8. <script>
  9. function myArray() {
  10. this.length = arguments.length;
  11. this.arr = []
  12. for (var i = 0; i < this.length; i++) {
  13. this[i] = arguments[i];
  14. this.arr[i] = arguments[i]; //也可以把数组转到一个单独的属性里去操作
  15. }
  16. this.sort = function (order = false) {
  17. if(typeof order == 'function'){
  18. var a = this.arr[0];
  19. var b = this.arr[1];
  20. order = order(a, b) > 0 ? true : false;
  21. }
  22. for (var i = 0; i < this.length; i++) {
  23. for (var j = 0; j < this.length - 1 - i; j++) {
  24. if (order) {
  25. if (this[j] < this[j + 1]) {
  26. var min = this[j];
  27. this[j] = this[j + 1];
  28. this[j + 1] = min;
  29. }
  30. } else {
  31. if (this[j] > this[j + 1]) {
  32. var max = this[j];
  33. this[j] = this[j + 1];
  34. this[j + 1] = max;
  35. }
  36. }
  37. }
  38. }
  39. return this;
  40. }
  41. this.reverse = function () {
  42. var arrReversed = [];
  43. var j = 0;
  44. for (var i = this.length - 1; i >= 0; i--) {
  45. arrReversed[j] = this[i];
  46. j++;
  47. }
  48. return arrReversed;
  49. }
  50. this.max = function () {
  51. var max = this[0];
  52. for (var i = 1; i < this.length; i++) {
  53. if (this[i] > max) {
  54. max = this[i];
  55. }
  56. }
  57. return max;
  58. }
  59. this.min = function () {
  60. var min = this[0];
  61. for (var i = 1; i < this.length; i++) {
  62. if (this[i] < min) {
  63. min = this[i]
  64. }
  65. }
  66. return min;
  67. }
  68. this.shift = function () {
  69. var temp = this[0];
  70. this.length--;
  71. for (var i = 0; i < this.length; i++) {
  72. this[i] = this[i + 1]
  73. }
  74. delete this[this.length];
  75. return temp;
  76. }
  77. }
  78. var arrObj = new myArray(1, 3, 5, 7, 2, 4, 6, 8);
  79. var sortedArr = arrObj.sort(function (a, b) {
  80. return a - b;
  81. })
  82. console.log(sortedArr);
  83. console.log(arrObj.reverse());
  84. console.log(arrObj.max());
  85. console.log(arrObj.min());
  86. </script>
  87. </body>
  88. </html>

js对象模拟数组