Blogger Information
Blog 10
fans 0
comment 0
visits 4918
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
js对象模拟数组
人生如梦
Original
532 people have browsed it

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

  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>

Correcting teacher:PHPzPHPz

Correction status:qualified

Teacher's comments:不知道返回什么,取决你模拟的什么,可以无返回值,也可以有,可以返回true表示排序成功,返回false表示返回失败
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post