Correcting teacher:PHPz
Correction status:qualified
Teacher's comments:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>JS对象模拟数组</title>
</head>
<body>
<script>
function MyArray() {
this.length = arguments.length;
for(var i=0; i<arguments.length; i++) {
this[i] = arguments[i];
}
this.push = function (s){
this[this.length]=s;
this.length++;
return this.length;
}
this.pop = function (){
var popdata = this[this.length-1];
delete this[this.length-1];
this.length--;
return popdata;
}
this.toString = function (){
var result = "";
var j = ',';
for (var i = 0; i<this.length-1; i++){
result += this[i];
result += j;
}
result += this[i];
return result;
}
this.sort = function sort(arr, flag=true) {
for(var i=0; i<arr.length-1; i++) {
for (var j = 0; j < arr.length-i-1; j++) {
if(flag) {
var swap = arr[j]
if (arr[j] > arr[j + 1]) {
arr[j] = arr[j + 1];
arr[j + 1] = swap;
}
}else{
if (arr[j] < arr[j + 1]) {
arr[j] = arr[j + 1];
arr[j + 1] = swap;
}
}
}
}
return arr;
}
this.max = function arrmax(arr) {
var max = arr[0];
for(var i=0; i<arr.length; i++) {
if(arr[i]>max)
max=arr[i];
}
return max;
}
this.min = function arrmin(arr) {
var min = arr[0];
for(var i=0; i<arr.length; i++) {
if(arr[i]<min)
min=arr[i];
}
return min;
}
this.reverse = function() {
var result = [];
for(var i = 0; i < this.length; i++) {
result[result.length] = this[this.length - i - 1];
}
for(var i = 0; i < result.length; i++) {
this[i] = result[i];
}
return this;
}
}
var arr = new MyArray(1,4,9,3,7)
console.log(arr.push("hello"))
console.log(arr.push("world"))
console.log(arr.toString())
console.log(arr.pop())
console.log(arr.pop())
console.log(arr.sort(arr,true))
console.log(arr.max(arr))
console.log(arr.min(arr))
console.log(arr.reverse())
</script>
</body>
</html>
数组对象的push与pop方法分别在数组的尾部添加与删除元素。
sort() 方法用于对数组的元素进行排序。
max()、min()取数组参数中的最大值、最小值