那么,这是一个字形:
完成方法/函数,以便将破折号/下划线分隔的单词转换为驼峰式大小写。只有当原始单词大写时,输出中的第一个单词才应该大写(称为上驼峰大小写,也常称为Pascal大小写)。
的例子"the-stealth-warrior"变成了"隐形勇士"。"The_Stealth_Warrior"被转换为"thestealthwarrior">
我想出了这个解决方案(在谷歌的一点帮助下):
function toCamelCase(str) {
const arrChar = Array.from(str)[0];
let result = '';
if (arrChar !== arrChar.toUpperCase()) {
result += str
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (m, chr) => chr.toUpperCase());
} else if (arrChar === arrChar.toUpperCase()) {
result += (' ' + str)
.toLowerCase()
.replace(/[^a-zA-Z0-9]+(.)/g, (m, ch) => ch.toUpperCase());
}
return result;
}
它在Vs code中工作完美,但CodeWars给了我这个:
TypeError: Cannot read property 'toUpperCase' of undefined
at toCamelCase
at it
at begin
at it
at describe
at /runner/frameworks/javascript/cw-2.js:152:11
at Promise._execute
at Promise._resolveFromExecutor
at new Promise
at describe
at /home/codewarrior/index.js:23:5
at /home/codewarrior/index.js:33:5
at Object.handleError
知道为什么吗?提前感谢……
在codewars中,他们提供的第一个测试用例是一个空字符串。因此array.from(")[0]将产生undefined并在稍后导致错误。可以通过检查字符串是否为空并返回它来避免这种情况。我建议总是寻找任务定义中描述的边缘情况,并从它们开始您的逻辑。
试试这个
const arrChar = Array.from(str)[0] ?? '';
给函数的参数可能是一个空字符串,这实际上可能导致此属性'toUpperCase'未定义问题。主要原因包括:
- 在未初始化为字符串的类属性上调用方法
- 在不存在的数组索引上调用方法
检查一下arrChar的值
if(!Array.from(str)[0]){
arrChar = "";
}
ch是任意对象,可以不是字符串,ch在ch.toUpperCase()