¥
立即购买

JavaScript循环生成器

7 浏览
1 试用
0 购买
Dec 8, 2025更新

本提示词专为JavaScript开发场景设计,能够根据用户指定的循环条件和输出语言要求,生成符合最佳实践的while循环代码。通过结构化的工作流程,确保输出的代码具备技术准确性、逻辑清晰性和可维护性。特别适用于教学演示、代码审查和项目开发等场景,帮助开发者快速实现基于特定条件的循环逻辑,同时提供详细的代码解释和潜在优化建议。

循环代码实现

/**
 * 在 items 中按顺序查找第一个满足条件的元素。
 * 使用 while (index < items.length && !foundTarget) 作为循环条件。
 *
 * @param {Array} items - 待搜索的数组
 * @param {(item: any, index: number, array: Array) => boolean} isMatch - 判定函数,返回 true 表示命中
 * @returns {{ foundTarget: boolean, matchedItem: any, index: number }}
 *          foundTarget: 是否找到目标
 *          matchedItem: 命中的元素(未找到时为 undefined)
 *          index: 命中元素的索引(未找到时为 -1)
 */
function findFirstMatch(items, isMatch) {
  // 参数校验,避免运行时错误
  if (!Array.isArray(items)) {
    throw new TypeError('items 必须是数组');
  }
  if (typeof isMatch !== 'function') {
    throw new TypeError('isMatch 必须是函数');
  }

  // 初始化循环相关变量
  let index = 0;           // 当前扫描位置
  let foundTarget = false; // 是否已找到目标
  let matchedItem;         // 命中的元素
  let resultIndex = -1;    // 命中索引

  // 核心循环:当索引未越界且尚未找到目标时继续
  while (index < items.length && !foundTarget) {
    const item = items[index];

    // 判定当前元素是否符合条件
    if (isMatch(item, index, items)) {
      foundTarget = true;
      matchedItem = item;
      resultIndex = index;

      // 虽然 while 条件已经依赖 foundTarget,但为了可读性与立即退出,这里显式 break
      break;
    }

    // 推进指针,避免死循环
    index += 1;
  }

  return { foundTarget, matchedItem, index: resultIndex };
}

/* 使用示例:
const items = [{ id: 1 }, { id: 2 }, { id: 3 }];
const targetId = 2;
const res = findFirstMatch(items, (it) => it.id === targetId);
// 期望:res => { foundTarget: true, matchedItem: { id: 2 }, index: 1 }
console.log(res);
*/

代码解释

  • 循环逻辑:

    • 初始化 index 为 0,foundTarget 为 false。
    • 使用 while (index < items.length && !foundTarget) 控制循环:
      • index < items.length 确保不越界。
      • !foundTarget 确保一旦命中即停止继续扫描。
    • 每轮循环调用 isMatch 判断当前元素是否命中,命中后更新 foundTarget、matchedItem、resultIndex,并使用 break 立即退出。
    • 未命中则将 index 自增,推进到下一项。
  • 变量作用:

    • index:当前检查的数组索引,驱动迭代。
    • foundTarget:标记是否已找到目标,参与循环条件与退出判断。
    • matchedItem:保存命中的元素,作为结果返回。
    • resultIndex:记录命中元素的索引,未找到时为 -1。
  • 退出条件:

    • 正常扫描完成:index >= items.length,未找到目标。
    • 提前退出:isMatch 返回 true,将 foundTarget 设为 true 并 break。

注意事项

  • 必须保证 index 在每次循环末尾递增,否则会导致死循环。
  • 不要在循环过程中修改 items(尤其是增删元素)或其长度,否则可能造成越界判断与数据不一致。
  • 判定函数 isMatch 应保持纯函数属性(无副作用),避免影响可预测性。
  • 当数组可能包含“空洞”(稀疏数组)时,访问 items[index] 可能得到 undefined,请在 isMatch 中做好判空处理。
  • 若 isMatch 需要异步逻辑(返回 Promise),请改用异步可迭代方案,while 不能直接 await 条件判断。

优化建议

  • 性能与可读性:
    • 如果 items 在循环中不会被修改,可在循环外缓存长度,减少属性访问开销:
      • 例如:const len = items.length; while (index < len && !foundTarget) { ... }
      • 注意:这会与“动态长度”脱钩,适用于只读场景。
    • 当前实现已在命中时使用 break 立即退出,避免多余判断,提升可读性。
  • 现代替代方案(更语义化):
    • 使用 Array.prototype.findIndex: const idx = items.findIndex((it, i, arr) => isMatch(it, i, arr)); const foundTarget = idx !== -1; const matchedItem = foundTarget ? items[idx] : undefined;
      • 适合需要简洁表达的场景。
    • 使用 Array.prototype.find: const matchedItem = items.find(isMatch); const foundTarget = matchedItem !== undefined; const idx = foundTarget ? items.indexOf(matchedItem) : -1;
      • 适合直接获取元素的场景(注意 indexOf 对对象引用相等)。
    • 使用 for...of 搭配 entries(): for (const [i, item] of items.entries()) { if (isMatch(item, i, items)) { ... break; } }
      • 可读性高,适合需要索引又想避免手动维护 index 的场景。
  • 异步判定函数场景:
    • 若 isMatch 为异步函数,请使用 for...of + await: for (const [i, item] of items.entries()) { if (await isMatch(item, i, items)) { ... break; } }
    • 或使用 for-await-of(当 items 为异步可迭代时)。

Loop Implementation

/**
 * Polls until a readiness condition is met, a timeout occurs, or retries are exhausted.
 * The loop condition follows:
 * (now() - startTime) < timeoutMs && !isReady && retries < maxRetries
 *
 * @param {Function} checkReady - Async/sync function that returns a boolean indicating readiness.
 * @param {Object} options
 * @param {number} options.timeoutMs - Maximum total wait time in milliseconds.
 * @param {number} options.maxRetries - Maximum number of failed checks allowed.
 * @param {number} [options.intervalMs=100] - Delay between checks to avoid a busy loop.
 * @returns {Promise<{ ready: boolean, retries: number, elapsedMs: number }>}
 */
async function waitUntilReady(checkReady, { timeoutMs, maxRetries, intervalMs = 100 }) {
  if (typeof checkReady !== 'function') {
    throw new TypeError('checkReady must be a function');
  }
  if (!Number.isFinite(timeoutMs) || timeoutMs < 0) {
    throw new RangeError('timeoutMs must be a non-negative number');
  }
  if (!Number.isInteger(maxRetries) || maxRetries < 0) {
    throw new RangeError('maxRetries must be a non-negative integer');
  }
  if (!Number.isFinite(intervalMs) || intervalMs < 0) {
    throw new RangeError('intervalMs must be a non-negative number');
  }

  // Use a monotonic clock when available to avoid issues with system clock adjustments.
  const now = (typeof performance !== 'undefined' && typeof performance.now === 'function')
    ? () => performance.now()
    : () => Date.now();

  const startTime = now();    // tracks when polling started
  let retries = 0;            // number of unsuccessful attempts
  let isReady = false;        // readiness state returned by checkReady()

  // Sleep helper to avoid a tight loop.
  const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));

  while ((now() - startTime) < timeoutMs && !isReady && retries < maxRetries) {
    try {
      // Attempt to determine readiness.
      // Supports both sync and async checkReady implementations.
      isReady = await checkReady();
    } catch (err) {
      // Treat exceptions as a failed check; consider logging if needed.
      isReady = false;
    }

    if (isReady) break; // Exit early if the condition is met.

    // Count this as a failed attempt only when not ready.
    retries += 1;

    // Compute remaining time; do not oversleep past the timeout.
    const elapsed = now() - startTime;
    const remaining = Math.max(0, timeoutMs - elapsed);

    // Break if no time remains or retries will stop the next loop.
    if (remaining === 0 || retries >= maxRetries) break;

    // Sleep for a bounded interval to prevent CPU spin.
    await sleep(Math.min(intervalMs, remaining));
  }

  return {
    ready: isReady,
    retries,
    elapsedMs: now() - startTime,
  };
}

/* Example usage:
(async () => {
  const result = await waitUntilReady(async () => {
    // Replace with your real readiness check (e.g., probing an API or checking a flag).
    return Math.random() > 0.8;
  }, { timeoutMs: 3000, maxRetries: 10, intervalMs: 150 });

  console.log(result);
})();
*/

Code Explanation

  • Loop logic:
    • The while condition mirrors the provided one:
      • (now() - startTime) < timeoutMs: keep looping until total elapsed time exceeds the timeout.
      • !isReady: stop immediately when the check indicates readiness.
      • retries < maxRetries: allow up to maxRetries failed attempts.
    • Each iteration:
      1. Calls checkReady() and awaits its result (supports sync or async).
      2. If ready, break immediately.
      3. Otherwise, increment retries.
      4. Sleep for intervalMs (bounded by remaining time) to avoid a busy-spin.
  • Variable roles:
    • startTime: the timestamp at which polling begins; used to compute elapsed time.
    • timeoutMs: the maximum duration the loop is allowed to run.
    • isReady: current state returned by checkReady(); determines early exit.
    • retries: number of failed checks so far; bounds the number of iterations.
    • maxRetries: maximum number of failed attempts permitted.
  • Exit conditions:
    • Ready state achieved (isReady === true).
    • Elapsed time reaches or exceeds timeoutMs.
    • retries reaches maxRetries.

Notes

  • The implementation uses performance.now() when available to avoid issues caused by system clock changes; it falls back to Date.now() otherwise.
  • A small delay (intervalMs) prevents a CPU-intensive tight loop; avoid setting it to 0 unless absolutely necessary.
  • If checkReady() can throw, the code treats that as a failed attempt and continues; adjust handling if exceptions should be fatal in your context.
  • Validate inputs to prevent negative values or non-finite numbers that could cause unexpected behavior.

Optimization Suggestions

  • Backoff strategy: Replace the fixed interval with exponential backoff (e.g., Math.min(intervalMs * 2 ** retries, maxInterval)) to reduce load on external systems.
  • Abort support: Accept an AbortSignal and stop early if signal.aborted, which is useful for user-initiated cancellation.
  • Dedicated timers: If you need precise scheduling with many concurrent polls, consider a scheduler or reusing timers to reduce overhead.
  • Alternative approach: Use setInterval with clearInterval when you prefer event-style control, but ensure you clear the timer on any exit path and guard against overlapping async checks.

循环代码实现

'use strict';

/**
 * 指定された条件(queuePointer < queue.length && processedCount < batchLimit)で
 * キューを先頭から順に処理します(同期処理版)。
 *
 * 注意:
 * - processedCount は「試行した件数」を表します(成功/失敗を問わず進みます)。
 *   成功件数のみをカウントしたい場合は、try ブロック内で加算する実装に変更してください。
 *
 * @param {any[]} queue - 処理対象の配列。ループ中に長さを変更しないことを推奨します。
 * @param {number} batchLimit - 1バッチで試行する最大件数(0以上の整数)。
 * @param {number} startPointer - 開始インデックス(0以上の整数、範囲外は自動で丸め込み)。
 * @param {(item:any, index:number)=>void} handle - 各要素を処理する関数(同期)。
 * @returns {{ nextPointer: number, attempted: number, errors: Error[] }}
 */
function processBatch(queue, batchLimit, startPointer = 0, handle = (item) => void item) {
  // 入力バリデーション(早期失敗で安全性を確保)
  if (!Array.isArray(queue)) {
    throw new TypeError('queue は配列である必要があります。');
  }
  if (!Number.isInteger(batchLimit) || batchLimit < 0) {
    throw new TypeError('batchLimit は 0 以上の整数である必要があります。');
  }
  if (!Number.isInteger(startPointer) || startPointer < 0) {
    throw new TypeError('startPointer は 0 以上の整数である必要があります。');
  }
  if (typeof handle !== 'function') {
    throw new TypeError('handle は関数である必要があります。');
  }

  // 反復用ポインタ(開始位置は配列長を超えないように丸める)
  let queuePointer = Math.min(startPointer, queue.length);
  // 今回のバッチで試行した件数
  let processedCount = 0;
  // エラーを収集(必要に応じてロギング/監視システムへ送信)
  const errors = [];

  // ループ条件:
  // - まだ未処理の要素が残っている(queuePointer < queue.length)
  // - かつ、今回のバッチの上限に達していない(processedCount < batchLimit)
  while (queuePointer < queue.length && processedCount < batchLimit) {
    const item = queue[queuePointer];

    try {
      // 各要素の処理(同期)
      // ここで例外が発生しても finally でポインタとカウントを進めるため無限ループになりません。
      handle(item, queuePointer);
    } catch (err) {
      // 個別要素の失敗は収集して継続(バッチ全体は止めない)
      errors.push(err instanceof Error ? err : new Error(String(err)));
    } finally {
      // 次の要素へ進む(試行件数も加算)
      queuePointer += 1;
      processedCount += 1;
    }
  }

  return {
    nextPointer: queuePointer, // 次回再開時の開始位置
    attempted: processedCount, // 今回試行した件数(成功/失敗を含む)
    errors,                    // 個別エラー一覧
  };
}

// 使用例:
// const result = processBatch(myQueue, 100, 0, (item, index) => {
//   // TODO: 各要素の処理ロジック
// });

代码解释

  • 循环逻辑:

    • while の条件は「未処理要素が残っている」かつ「バッチ上限未満」の両方を満たす間だけ繰り返します。
    • 各反復で現在の要素を handle に渡して処理します。例外が発生しても finally で queuePointer と processedCount を必ず進め、無限ループを防止します。
    • エラーは収集して継続するため、1件の失敗でバッチ全体が停止しません。
  • 变量作用:

    • queuePointer: 現在処理中の配列インデックス。各反復後に必ず +1。
    • processedCount: 今回のバッチで試行した件数。各反復後に必ず +1。
    • batchLimit: 今回のバッチの試行上限。条件で processedCount と比較。
    • queue.length: 配列の要素数。条件で queuePointer と比較。
    • errors: 要素処理中に発生した例外を格納します。
  • 退出条件:

    • queuePointer が queue.length に到達したとき(要素をすべて処理/走査し終えた)。
    • processedCount が batchLimit に到達したとき(バッチの上限に達した)。

注意事项

  • ループ中に queue の長さを変更しないことを推奨します。length を動的に変えると境界条件が複雑になり、意図しないスキップや二重処理の原因になります。
  • processedCount は「試行件数」です。成功件数のみを制限したい場合は、try 内で成功時のみ processedCount を加算し、finally では queuePointer のみ進めてください。その場合、失敗が連続すると多くの要素を走査する点に注意してください。
  • handle が重い処理を行う場合は、ループ内で不要なクロージャ生成・ログ出力・DOM 操作などを避け、処理時間を最小化してください。
  • startPointer が範囲外でも Math.min で丸め込んで開始するため、安全に走査が始まります。
  • エラーの握りつぶしは禁物です。ここでは収集して返却しているため、呼び出し元で必ず監視・再試行・隔離などの対応を検討してください。

优化建议

  • パフォーマンスと可読性:
    • queue を変更しない前提なら、ループ前に const end = queue.length; としてスナップショットを取り、while (queuePointer < end && processedCount < batchLimit) とすると length 取得のオーバーヘッドと動的変化の影響を避けられます。
    • for ループでの表現も明快です。 例: for (let i = startPointer, attempts = 0, end = queue.length; i < end && attempts < batchLimit; i++, attempts++) { try { handle(queue[i], i); } catch (e) { errors.push(e); } }
  • 非同期処理が必要な場合:
    • async/await を使うなら、関数自体を async にして await handle(...) を使用してください。例: async function processBatchAsync(queue, batchLimit, startPointer, handleAsync) { let ptr = Math.min(startPointer, queue.length), tried = 0; const errs = []; while (ptr < queue.length && tried < batchLimit) { try { await handleAsync(queue[ptr], ptr); } catch (e) { errs.push(e); } finally { ptr++; tried++; } } return { nextPointer: ptr, attempted: tried, errors: errs }; }
    • 高スループットが必要なら、上限付き並行実行(例: Promise プール)を検討してください。ただし並行数制御や順序保証、再試行ポリシーに注意が必要です。
  • データ構造:
    • キューとして shift を多用すると O(n) で非効率です。今回のようにインデックスで進めるか、両端キュー(Deque)やリングバッファを検討してください。

示例详情

解决的问题

用一句话概括:把“写 while 循环”这件高频又易出错的小事,交给专业提示词,省时、省心、更稳。

  • 面向研发:根据你给出的循环条件,即时产出规范、易读、可维护的 while 代码,并自动规避常见陷阱(如死循环、边界遗漏)。
  • 面向教学:同步生成清晰注释、变量说明与执行流程讲解,助力课堂/培训资料一键成型。
  • 面向评审:内置注意事项与风险提示,提前暴露潜在问题,减少反复修改与沟通成本。
  • 面向团队:统一风格与最佳实践,提升可读性与一致性,降低新人上手与交接难度。
  • 多语言说明:可按需输出中文/英文等说明文案,便于跨团队协作与对外文档。
  • 一次生成,多重价值:代码实现 + 原理解释 + 注意事项 + 优化建议,覆盖从开发到复盘的完整闭环。

适用用户

前端工程师

基于交互状态轻松生成列表遍历、滚动检测、输入校验等循环;快速插入注释与退出条件;减少调试时间,提升提测效率。

Node.js后端开发

为队列消费、任务重试、定时轮询等场景生成稳健循环;内置超时与中止建议;降低线上宕机与资源占用风险。

编程讲师与教研人员

一键产出教学示例与讲解要点;展示变量作用、边界处理与常见误区;用于课堂演示、练习讲评与教材编写。

特征总结

按业务条件一键生成规范while循环,自动补齐初始化、判断与迭代细节
内置最佳实践与命名建议,输出即读即用,减少后续重构与沟通成本
自动添加清晰注释与使用说明,便于团队协作、代码评审与后续维护
智能识别潜在死循环与边界风险,生成时同步给出修正与防护方案
支持教学演示友好输出,拆解循环逻辑、退出条件与变量作用
可按需求切换讲解语言与语气风格,适配初学者培训或资深同事交流
给出性能与可读性优化建议,并提供替代写法,帮助快速权衡取舍
支持模板化复用常见循环模式,一键调用,批量减少重复劳动
生成前先做条件语义核对,确保代码与预期业务规则保持一致

如何使用购买的提示词模板

1. 直接在外部 Chat 应用中使用

将模板生成的提示词复制粘贴到您常用的 Chat 应用(如 ChatGPT、Claude 等),即可直接对话使用,无需额外开发。适合个人快速体验和轻量使用场景。

2. 发布为 API 接口调用

把提示词模板转化为 API,您的程序可任意修改模板参数,通过接口直接调用,轻松实现自动化与批量处理。适合开发者集成与业务系统嵌入。

3. 在 MCP Client 中配置使用

在 MCP client 中配置对应的 server 地址,让您的 AI 应用自动调用提示词模板。适合高级用户和团队协作,让提示词在不同 AI 工具间无缝衔接。

AI 提示词价格
¥20.00元
先用后买,用好了再付款,超安全!

您购买后可以获得什么

获得完整提示词模板
- 共 703 tokens
- 2 个可调节参数
{ 循环条件 } { 输出语言 }
获得社区贡献内容的使用权
- 精选社区优质案例,助您快速上手提示词
使用提示词兑换券,低至 ¥ 9.9
了解兑换券 →
限时半价

不要错过!

半价获取高级提示词-优惠即将到期

17
:
23
小时
:
59
分钟
:
59