模拟数组pop,push,toString和冒泡排序(sort的使用)
程序员文章站
2022-03-13 13:55:28
...
图片展示
代码展示
<script>
//创建一个对象
function MaArray(){
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 j=0;j<this.length-1;j++){
result+=this[j];
result+=j;
}
result+=this[j];
return result;
}
//最大值
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.sort=function(){
//定义x用于替换
var x=0;
//外层循环,控制趟数,每一次找到一个最大值
for(var i=0;i<this.length-1;i++){
// 内层循环,控制比较的次数,并且判断两个数的大小
for(var j=0;j<this.length-1-i;j++){
//从小到大的冒泡排序
if(this[j]>this[j+1]){
x=this[j];
this[j]=this[j+1];
this[j+1]=x;
}
}
}
return this;
}
}
var arr=new MaArray(11,3,55,88,99,5,'abc');
console.log(arr);
console.log(arr.push('cs'));
console.log(arr.pop());
console.log(arr.max());
console.log(arr.min());
console.log(arr.sort());
</script>
下一篇: 可编辑的表格