×
¥
查看详情
🔥 会员专享 文生文 代码生成

JavaScript循环生成器

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

🎯 可自定义参数(2个)

循环条件
循环执行的条件表达式
输出语言
输出内容的语言

🎨 效果示例

循环代码实现

/**
 * 在 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)やリングバッファを検討してください。

示例详情

📖 如何使用

30秒出活:复制 → 粘贴 → 搞定
与其花几十分钟和AI聊天、试错,不如直接复制这些经过千人验证的模板,修改几个 {{变量}} 就能立刻获得专业级输出。省下来的时间,足够你轻松享受两杯咖啡!
加载中...
💬 不会填参数?让 AI 反过来问你
不确定变量该填什么?一键转为对话模式,AI 会像资深顾问一样逐步引导你,问几个问题就能自动生成完美匹配你需求的定制结果。零门槛,开口就行。
转为对话模式
🚀 告别复制粘贴,Chat 里直接调用
无需切换,输入 / 唤醒 8000+ 专家级提示词。 插件将全站提示词库深度集成于 Chat 输入框。基于当前对话语境,系统智能推荐最契合的 Prompt 并自动完成参数化,让海量资源触手可及,从此彻底告别"手动搬运"。
即将推出
🔌 接口一调,提示词自己会进化
手动跑一次还行,跑一百次呢?通过 API 接口动态注入变量,接入批量评价引擎,让程序自动迭代出更高质量的提示词方案。Prompt 会自己进化,你只管收结果。
发布 API
🤖 一键变成你的专属 Agent 应用
不想每次都配参数?把这条提示词直接发布成独立 Agent,内嵌图片生成、参数优化等工具,分享链接就能用。给团队或客户一个"开箱即用"的完整方案。
创建 Agent

✅ 特性总结

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

🎯 解决的问题

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

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

🕒 版本历史

当前版本
v2.1 2024-01-15
优化输出结构,增强情节连贯性
  • ✨ 新增章节节奏控制参数
  • 🔧 优化人物关系描述逻辑
  • 📝 改进主题深化引导语
  • 🎯 增强情节转折点设计
v2.0 2023-12-20
重构提示词架构,提升生成质量
  • 🚀 全新的提示词结构设计
  • 📊 增加输出格式化选项
  • 💡 优化角色塑造引导
v1.5 2023-11-10
修复已知问题,提升稳定性
  • 🐛 修复长文本处理bug
  • ⚡ 提升响应速度
v1.0 2023-10-01
首次发布
  • 🎉 初始版本上线
COMING SOON
版本历史追踪,即将启航
记录每一次提示词的进化与升级,敬请期待。

💬 用户评价

4.8
⭐⭐⭐⭐⭐
基于 28 条评价
5星
85%
4星
12%
3星
3%
👤
电商运营 - 张先生
⭐⭐⭐⭐⭐ 2025-01-15
双十一用这个提示词生成了20多张海报,效果非常好!点击率提升了35%,节省了大量设计时间。参数调整很灵活,能快速适配不同节日。
效果好 节省时间
👤
品牌设计师 - 李女士
⭐⭐⭐⭐⭐ 2025-01-10
作为设计师,这个提示词帮我快速生成创意方向,大大提升了工作效率。生成的海报氛围感很强,稍作调整就能直接使用。
创意好 专业
COMING SOON
用户评价与反馈系统,即将上线
倾听真实反馈,在这里留下您的使用心得,敬请期待。
加载中...