js 实现each
实现 each 方法
在 JavaScript 中,each 方法通常用于遍历数组或对象。以下是几种实现方式:
数组的 each 方法
Array.prototype.each = function(callback) {
for (let i = 0; i < this.length; i++) {
callback(this[i], i, this);
}
};
// 使用示例
const arr = [1, 2, 3];
arr.each((item, index) => {
console.log(`Index ${index}: ${item}`);
});
对象的 each 方法
Object.prototype.each = function(callback) {
for (const key in this) {
if (this.hasOwnProperty(key)) {
callback(this[key], key, this);
}
}
};
// 使用示例
const obj = { a: 1, b: 2, c: 3 };
obj.each((value, key) => {
console.log(`Key ${key}: ${value}`);
});
通用 each 函数
function each(collection, callback) {
if (Array.isArray(collection)) {
for (let i = 0; i < collection.length; i++) {
callback(collection[i], i, collection);
}
} else if (typeof collection === 'object' && collection !== null) {
for (const key in collection) {
if (collection.hasOwnProperty(key)) {
callback(collection[key], key, collection);
}
}
}
}
// 使用示例
each([1, 2, 3], (item, index) => {
console.log(item, index);
});
each({ a: 1, b: 2 }, (value, key) => {
console.log(key, value);
});
注意事项
- 修改内置原型(如
Array.prototype或Object.prototype)可能会引起冲突,谨慎使用 - 使用
hasOwnProperty检查可以避免遍历到原型链上的属性 - 回调函数的参数通常遵循
(value, index/key, collection)的模式







