js 中 自定义数组的的插入,删除实现
function Arrays() {
//创建一个数组
this.array = new Array();//[];
//获取数组长度
this.size = function () {
return this.array.length;
}
//初始化数组
this.init = function (data) {
if (data) {
for (let i = 0; i < data.length; i++) {
const cur = data[i];
this.array[i] = cur;
}
return this.array;
}
return data;
}
//获取数组信息
this.getArray =function () {
return this.array;
}
//判断数组是否为空
this.isEmpty = function () {
return (this.array.length < 1);
}
//清空数组
this.clear = function () {
this.array = [];
this.array.length = 0;
return this.array;
}
//像数组末尾添加一个或者多个元素,并返回新的长度
this.push = function (data) {
this.array[this.array.length] = data;
return this.array.length;
}
//删除数组最后一个元素,并返回
this.pop = function () {
let n = this.array.length;
if (n == 0) {
return;
}
let value = this.array[n - 1];
this.array[n - 1] = null;
this.array.length -= 1;
return value;
}
//删除并返回数组的第一个元素
this.shift = function () {
let n = this.array.length;
if (n == 0) return;
let value = this.array[0];
let newarr = [];
for (let i = 1; i < this.array.length; i++) {
newarr[i - 1] = this.array[i];
}
this.array = [];
for (let j = 0; j < newarr.length; j++) {
this.array[j] = newarr[j];
}
return value;
}
//向数组中插入元素.如果插入位置大于数组长度,默认插在最后一位
this.addData = function (index, value) {
let n = this.array.length;
if (index > n) index = n;
this.array.length += 1;
for (let i = 0; i < this.array.length; i++) {
if (index <= i) {
let tmp = this.array[i];
this.array[i] = value;
value = tmp;
}
}
return this.array;
}
//删除指定位置元素,默认从第0位开始。索引超出范围,不执行删除操作
this.deletData = function (index) {
let n = this.array.length;
if (index >= n) return;
this.array[index] = null;
let tmp = null;
for (let i = 0; i < this.length; i++) {
if (index <= i && (i + 1) <= this.array.length) {
tmp = this.array[i + 1];
this.array[i] = tmp;
}
}
this.array.length -= 1;
return this.array;
}
}