下面是卡塔:
完成该方法/函数,以便将破折号/下划线分隔词转换为骆驼大小写。输出中的第一个词只有在原来的单词被大写时才能大写(称为上骆驼大小写,也常被称为Pascal大小写)。
例如,将“隐形战士”转换为"theStealthWarrior“"The_Stealth_Warrior”转换为"TheStealthWarrior“。
我想出了一个解决方案(在Google的帮助下):
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代码中工作得很好,但是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知道为什么吗?提前谢谢..。
发布于 2022-07-05 06:49:00
在代码战中,它们提供的第一个测试用例是一个空字符串。因此,array.from("")将产生未定义的结果,并在稍后导致错误。这可以通过检查字符串是否为空来避免,如果为空则返回。我建议始终寻找在任务定义中描述的边缘情况,并开始使用它们的逻辑。
发布于 2022-07-05 06:44:22
尝尝这个。
const arrChar = Array.from(str)[0] ?? '';发布于 2022-07-05 06:49:01
给函数的参数可能是一个空字符串,这实际上可能导致这个属性'toUpperCase‘未定义的问题。造成这种情况的主要原因包括:
的数组索引上的方法
因此,检查arrChar值。
if(!Array.from(str)[0]){
arrChar = "";
}https://stackoverflow.com/questions/72864973
复制相似问题