使用js实现一个与数组的forEach函数一样功能的函数

34 阅读1分钟

"```markdown 使用js实现一个与数组的forEach函数一样功能的函数

答案:

function myForEach(arr, callback) {
  for (let i = 0; i < arr.length; i++) {
    callback(arr[i], i, arr);
  }
}

// 示例用法
const array = [1, 2, 3];
myForEach(array, (item, index, arr) => {
  console.log(`Item: ${item}, Index: ${index}, Array: ${arr}`);
});