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

JavaScript实现驼峰命名拆分函数出错,请求问题排查

问题分析与解决方案

你的代码核心问题是:当你在newStr中插入空格后,数组长度会增加,而循环变量i基于原字符串长度遍历,后续字符的索引会被插入的空格偏移,导致大写字母的判断位置彻底混乱。比如处理camelCasing时,插入第一个空格后newStr长度从11变为12,接下来i=6对应的原字符串字符是a,但newStr[6]已经变成了C,后续逻辑全部出错。

修正方案1:倒序遍历数组

倒序遍历可以避免插入空格干扰未处理部分的索引(从末尾往开头处理,插入的空格不会改变前面未处理字符的位置):

function solution(string) {
  let newStr = string.split("");
  // 倒序遍历,规避插入空格后的索引偏移问题
  for (let i = newStr.length - 1; i >= 0; i--) {
    if (newStr[i] === newStr[i].toUpperCase()) {
      newStr.splice(i, 0, ' ');
    }
  }
  return newStr.join("");
}

修正方案2:直接构建新字符串(更高效)

放弃修改数组,直接遍历原字符串逐个拼接结果,逻辑更清晰:

function solution(string) {
  let result = '';
  for (const char of string) {
    result += char === char.toUpperCase() ? ' ' + char : char;
  }
  return result;
}

最优方案:正则表达式(最简洁)

利用正则匹配所有大写字母,直接替换为空格+大写字母,一行代码解决问题:

function solution(string) {
  return string.replace(/([A-Z])/g, ' $1');
}

测试验证:

console.log('camelCasing: ', solution('camelCasing')); // 输出 "camel Casing"
console.log('camelCasingTest: ', solution('camelCasingTest')); // 输出 "camel Casing Test"
console.log('identifier: ', solution('identifier')); // 输出 "identifier"
console.log('empty: ', solution('')); // 输出 ""

内容的提问来源于stack exchange,提问作者Nicolette DeVille

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.18 14:55:16