<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>列表</title>
</head>
<body>
</body>
<script>
function List() {
this.dataStore = [];
this.append1 = function (data) {
//获得数组的长度
var length = this.length();
if(length==0) {
this.dataStore[0] = data;
}
else {
for(var i=length-1;i>=0;i--) {
if(this.dataStore[i]<data) {
this.insert(data,this.dataStore[i]);
return;
}
}
this.insertBefore(data,this.dataStore[0]);
}
}
this.length = function () {
//获得数组的长度
var length = this.dataStore.length;
return length;
}
//如果找到当前的数据,就返回当前数据的下标,如果没有找到数据就返回-1
this.find = function (data) {
//1,获得数组的长度
var length = this.length();
//2,设置返回数据的下标
var index = -1;
//3,遍历数据
for (var i = 0; i < length; i++) {
if (data == this.dataStore[i]) {
index = i;
return index;
}
}
return index;
}
this.forEach = function (call) {
//1,获得数组的长度
var length = this.length();
//2,遍历数据
for (var i = 0; i < length; i++) {
call(this.dataStore[i]);
}
}
//在after后面插入数据,如果after有数据,就插入在after后面,如果after没有数据,就把data插入到最后面的数据
this.insert = function (data, after) {
//1,找到当前after数据的下标
var index = this.find(after);
if (index == -1) {
//向队列后面添加数据
this.append(data);
} else {
// 1,2,3,4,5,5,7,9
var length = this.length();
for (var i = length - 1; i > index; i--) {
this.dataStore[i + 1] = this.dataStore[i]
}
this.dataStore[index + 1] = data;
}
}
//在before前面插入数据,如果before有数据,就插入在before前面,如果before没有数据,就把data插入到最前面的数据
this.insertBefore = function (data,before) {
//1,找到当前before数据的下标
var index = this.find(before);
var length = this.length();
if(index==-1) {
for (var i = length - 1; i >= 0; i--) {
this.dataStore[i + 1] = this.dataStore[i]
}
this.dataStore[0] = data;
}
else {
for (var i = length - 1; i >= index; i--) {
this.dataStore[i + 1] = this.dataStore[i]
}
this.dataStore[index] = data;
}
}
}
var list = new List();
list.append1(1);
list.append1(2);
list.append1(0);
list.append1(10);
list.append1(9);
list.forEach(function (data) {
console.log(data);
});
</script>
</html>
js使用在指定数据前面或后面插入数据,对List数据排序
猜你喜欢
转载自blog.csdn.net/qq_34607371/article/details/81085779
今日推荐
周排行