博主信息
博文 10
粉丝 0
评论 0
访问量 7346
热门教程
更多>
最新下载
更多>
网站特效
网站源码
网站素材
前端模板
js对象模拟数组
人生如梦
原创
667人浏览过

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

  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>

批改老师:PHPzPHPz

批改状态:合格

老师批语:不知道返回什么,取决你模拟的什么,可以无返回值,也可以有,可以返回true表示排序成功,返回false表示返回失败
本博文版权归博主所有,转载请注明地址!如有侵权、违法,请联系admin@php.cn举报处理!
全部评论 文明上网理性发言,请遵守新闻评论服务协议
0条评论
作者最新博文
关于我们 免责申明 意见反馈 讲师合作 广告合作 最新更新 English
php中文网:公益在线php培训,帮助PHP学习者快速成长!
关注服务号 技术交流群
PHP中文网订阅号
每天精选资源文章推送
PHP中文网APP
随时随地碎片化学习

Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号

  • 登录PHP中文网,和优秀的人一起学习!
    全站2000+教程免费学