Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:不知道返回什么,取决你模拟的什么,可以无返回值,也可以有,可以返回true表示排序成功,返回false表示返回失败
排序完了不知道要返回数组还是对象,先这样吧
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>object</title>
</head>
<body>
<script>
function myArray() {
this.length = arguments.length;
this.arr = []
for (var i = 0; i < this.length; i++) {
this[i] = arguments[i];
this.arr[i] = arguments[i]; //也可以把数组转到一个单独的属性里去操作
}
this.sort = function (order = false) {
if(typeof order == 'function'){
var a = this.arr[0];
var b = this.arr[1];
order = order(a, b) > 0 ? true : false;
}
for (var i = 0; i < this.length; i++) {
for (var j = 0; j < this.length - 1 - i; j++) {
if (order) {
if (this[j] < this[j + 1]) {
var min = this[j];
this[j] = this[j + 1];
this[j + 1] = min;
}
} else {
if (this[j] > this[j + 1]) {
var max = this[j];
this[j] = this[j + 1];
this[j + 1] = max;
}
}
}
}
return this;
}
this.reverse = function () {
var arrReversed = [];
var j = 0;
for (var i = this.length - 1; i >= 0; i--) {
arrReversed[j] = this[i];
j++;
}
return arrReversed;
}
this.max = function () {
var max = this[0];
for (var i = 1; i < this.length; i++) {
if (this[i] > max) {
max = this[i];
}
}
return max;
}
this.min = function () {
var min = this[0];
for (var i = 1; i < this.length; i++) {
if (this[i] < min) {
min = this[i]
}
}
return min;
}
this.shift = function () {
var temp = this[0];
this.length--;
for (var i = 0; i < this.length; i++) {
this[i] = this[i + 1]
}
delete this[this.length];
return temp;
}
}
var arrObj = new myArray(1, 3, 5, 7, 2, 4, 6, 8);
var sortedArr = arrObj.sort(function (a, b) {
return a - b;
})
console.log(sortedArr);
console.log(arrObj.reverse());
console.log(arrObj.max());
console.log(arrObj.min());
</script>
</body>
</html>