代码仓库
forEach
Array.prototype.lForEach = function (callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError(`${callback} must be a function`);
}
const array = this;
for (let i = 0; i < array.length; i++) {
// 判断对象本身(非原型链)是否含有该属性
if (array.hasOwnProperty(i)) {
callback.call(thisArg, array[i], i, array);
}
}
};map
Array.prototype.lMap = function (callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError(`${callback} must be a function`);
}
const array = this;
const resArr = new Array(array.length);
for (let i = 0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
const res = callback.call(thisArg, array[i], i, array);
resArr[i] = res;
}
}
return resArr;
};filter
Array.prototype.lFilter = function (callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError(`${callback} must be a function`);
}
const array = this;
const resArr = new Array();
let n = 0;
for (let i = 0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
const flag = callback.call(thisArg, array[i], i, array);
if (flag) {
resArr[n] = array[i];
n++;
}
}
}
return resArr;
};reduce
Array.prototype.lReduce = function (callback, initialValue) {
if (typeof callback !== 'function') {
throw new TypeError(`${callback} must be a function`);
}
if (this.length === 0 && initialValue === undefined) {
throw new TypeError('Reduce of empty array with no initial value');
}
// 初始化累加器和起始索引
let accumulator = initialValue !== undefined ? initialValue : this[0];
let startIdx = initialValue !== undefined ? 0 : 1;
for (let i = startIdx; i < this.length; i++) {
accumulator = callback(accumulator, this[i], i, this);
}
return accumulator;
};find
Array.prototype.lFind = function (callback, thisArg) {
if (typeof callback !== 'function') {
throw new TypeError(`${callback} must be a function`);
}
const array = this;
let target = null;
for (let i = 0; i < array.length; i++) {
if (array.hasOwnProperty(i)) {
const flag = callback.call(thisArg, array[i], i, array);
if (flag) {
target = array[i];
return target;
}
}
}
return undefined;
};flat
Array.prototype.lFlat = function (depth = 1) {
if (typeof depth !== 'number') {
throw new TypeError(`${depth} must be a number`);
}
let result = [];
this.forEach((item) => {
if (Array.isArray(item) && depth > 0) {
result = result.concat(item.lFlat(depth === Infinity ? depth : depth - 1));
} else {
result.push(item);
}
});
return result;
};原创
手写数组方法
本文采用 CC BY-NC-SA 4.0 许可协议,转载请注明出处。



评论交流
欢迎留下你的想法