用途

数组用来将一些较为复杂的数据组合的一起的参数序列

常用方法实现

push

向数组尾部追加元素,数组长度+1

1
2
3
Array.prototype._push = function (val) {
this[this.length] = val;
};

pop

删除数组尾部第一个元素,数组长度-1

1
2
3
4
5
Array.prototype._pop = function () {
var temp = this[this.length - 1];
this.length--;
return temp;
};

shift

删除数组头部第一个元素,数组长度 -1

1
2
3
4
5
6
7
8
Array.prototype._shift = function () {
var temp = this[0];
for (var i = 1; i < this.length; i++) {
this[i - 1] = this[i];
}
this.length--;
return temp;
};

unshift

数组头部添加一个元素,之前元素后移一位,长度 +1

1
2
3
4
5
6
7
8
Array.prototype._unshift = function () {
var arr = [...arguments, ...this];
this.length = arr.length;
for (var i = 0; i < arr.length; i++) {
this[i] = arr[i];
}
return this.length;
};

some

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Array.prototype._some = function (callback) {
if (typeof callback !== "function") {
return new TypeError("只能接受一个函数");
}
for (var i = 0; i < this.length; i++) {
if (callback(this[i])) {
return true;
}
}
return false;
};

const result = arr._some(function (itm) {
return itm == 2;
});

reduce

1
2
3
4
5
6
7
8
9
10
Array.prototype._reduce = function (reducer, init) {
for (var i = 0; i < this.length; i++) {
init = reducer(init, this[i], i, this);
}
return init;
};

const result = arr._reduce(function (prev, curr, index, array) {
return prev + curr;
}, 0);

splice

1
2
3
Array.prototype.together = function (arr) {
return [...this, ...arr];
};

together

Array.prototype.together = function (arr) { return […this, …arr]; };

includes

1
2
3
4
5
6
Array.prototype.include = function (val) {
const hasVal = this.some((item, index) => {
return item === val;
});
return hasVal;
};

toString

1
2
3
Array.prototype.toString = function () {
return this.join();
};

size

1
2
3
Array.prototype.size = function () {
return this.length;
};

delete

1
2
3
4
5
6
Array.prototype.delete = function (index, count) {
for (var i = index; i < this.length; i++) {
this[i] = this[i + count];
}
this.length = this.length - count;
};

addFirst

1
2
3
4
5
for (var i = this.length; i >= 0; i--) {
this[i] = this[i - 1];
}
this[0] = val;
return this;

unshift

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Array.prototype.insert = function (val, index) {
const _this = this;
if (val instanceof Array) {
val.forEach((itm, ind) => {
for (var i = this.length; i >= index + ind; i--) {
this[i] = this[i - 1];
}
this[index + ind] = itm;
});
} else {
for (var i = this.length; i >= index; i--) {
this[i] = this[i - 1];
}
this[index] = val;
}
return this;
};

remove

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
Array.prototype.removal = function () {
//方案一:
//利用对象的属性是唯一的特性,来实现去重
let list = {};
this.forEach((key) => {
if (list[key] == undefined) {
list[key] = 1;
}
});
// 方案二:
//利用链表,来实现去重
// let list = new LinkedList();
// this.forEach(key => {
// if (list.find(key) === false) {
// list.add(key);
// }
// });
// return list.convert2array();
//方案三
return Array.from(new Set(this));
};