You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript循环内函数实现问题:自定义rep函数无法运行求助

问题排查与修复

Hey there, let's break down why your code isn't working and fix it up! Your implementation has two key issues that prevent it from populating the label array correctly:

1. You defined an arrow function but never executed it

Inside your rep function's loop, you wrote i => { label.push(Unit ${i + 1}); } — this creates an arrow function, but you never actually run it! In the original example, the repeat function calls the passed-in action(i) to execute the callback logic. Without invoking that arrow function, nothing gets added to your array.

2. Your function is missing the callback parameter (breaking the original pattern)

The original repeat function is designed to be flexible: it takes a number n and a callback function that defines what to do on each iteration. Your rep function only accepts n and hardcodes the arrow function inside, which not only deviates from the example's intent but also removes the flexibility of passing different actions.


Fixed Version (Matching the Original Example's Pattern)

This fixes both issues by adding the callback parameter and actually invoking it in the loop:

function rep(n, action) { 
  for(let i = 0; i < n; i++){ 
    action(i); // Execute the callback with the current loop index
  } 
}

let label = [];
rep(5, i => { label.push(`Unit ${i + 1}`); }); // Pass your desired action as the callback
console.log(label); // Output: ["Unit 1", "Unit 2", "Unit 3", "Unit 4", "Unit 5"]

Simplified Version (If You Don't Need Callback Flexibility)

If you just want to directly generate the array without using a callback, you can simplify the code like this (no need to define unused arrow functions):

function rep(n) { 
  const label = [];
  for(let i = 0; i < n; i++){ 
    label.push(`Unit ${i + 1}`); // Directly add items to the array in the loop
  } 
  return label;
}

console.log(rep(5)); // Output: ["Unit 1", "Unit 2", "Unit 3", "Unit 4", "Unit 5"]

内容的提问来源于stack exchange,提问作者Akash RP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 13:47:47