驼峰字符串转空格分隔时循环逻辑异常问题求助
驼峰字符串拆分循环代码的问题修复建议
问题描述
输入字符串"camelCasingTest"时,当前循环代码输出结果为"camel Casin gTest",无法正确将驼峰式字符串拆分为空格分隔的单词。
原代码问题分析
原代码存在两个关键错误:
- 未定义变量引用:判断条件中使用了未声明的
str变量,应该替换为函数参数string或当前遍历的数组元素。 - 索引对应关系混乱:判断时依赖原字符串
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
相关产品推荐
相关产品推荐

