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

JavaScript循环重复字符串挑战问题求助

循环重复字符串的实现错误排查

题目要求

给定字符串s和数字n,返回一个新字符串,其中s的字符以循环方式连续重复n次。如果新字符串长度超过100,则截断为长度100。

错误写法分析

你尝试的两种写法都存在问题:

写法一问题

function circularRepeat(s, n) {
    n = Math.min(n, 100); // Ensure n doesn't exceed 100

  let result = "";
  for (let i = 0; i < n; i++) {
    result += s[i % s.length]; // Use modulo to select characters circularly
  }
  return result;
}
  • 未处理s为空字符串的边界情况:当s为空时,s.length为0,i % 0会触发运行时错误,导致代码崩溃。

写法二问题

function circularRepeat(s, n) {
    return n > 100 ? s.repeat(100) : s.repeat(n);
}
  • 完全误解了题目要求:s.repeat(n)是将整个字符串重复n次,比如s="ab"、n=3时会得到"ababab",但题目要求的是逐个字符循环取n次,正确结果应该是"aba"。

正确解法

先处理边界情况,再高效生成目标字符串:

function circularRepeat(s, n) {
    const maxLength = Math.min(n, 100);
    // 空字符串直接返回空
    if (s.length === 0) return "";
    // 计算完整重复次数和剩余需要取的字符数
    const fullRepeats = Math.floor(maxLength / s.length);
    const remainder = maxLength % s.length;
    // 拼接完整重复部分 + 剩余字符部分
    return s.repeat(fullRepeats) + s.slice(0, remainder);
}

或者用循环写法(处理空字符串情况):

function circularRepeat(s, n) {
    const maxLength = Math.min(n, 100);
    let result = "";
    const strLength = s.length;
    // 空字符串直接返回
    if (strLength === 0) return "";
    for (let i = 0; i < maxLength; i++) {
        result += s[i % strLength];
    }
    return result;
}

这两种写法都能正确处理所有情况:包括空字符串、n大于100、s长度大于n等场景。

内容的提问来源于stack exchange,提问作者M-Sev1

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 09:01:15