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

驼峰字符串转空格分隔时循环逻辑异常问题求助

驼峰字符串拆分循环代码的问题修复建议

问题描述

输入字符串"camelCasingTest"时,当前循环代码输出结果为"camel Casin gTest",无法正确将驼峰式字符串拆分为空格分隔的单词。

原代码问题分析

原代码存在两个关键错误:

  1. 未定义变量引用:判断条件中使用了未声明的str变量,应该替换为函数参数string或当前遍历的数组元素。
  2. 索引对应关系混乱:判断时依赖原字符串string的字符,但操作的是修改后的splittedString数组。插入空格后数组长度增加,string.charAt(i)会取到错误的字符,导致后续大写字母检测失效。

修复后的代码

function camelCase(string) {
    let splittedString = string.split('')

    for(let i = 0; i < splittedString.length; i++){
       // 检查当前数组元素是否为大写字母
       if(splittedString[i] === splittedString[i].toUpperCase()){
        splittedString.splice(i, 0, ' ')
        // 跳过插入的空格,避免重复处理
        i++
       }
    }
    return splittedString.join('')
}

修复说明

  • 替换未定义的str变量,直接使用当前遍历的splittedString[i]进行判断,确保索引与操作数组完全对应。
  • 插入空格后执行i++,跳过新增的空格元素,避免循环重复处理空格字符。

测试输入"camelCasingTest",将得到预期结果:camel Casing Test。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 18:32:50