[英]Receiving TypeError: Cannot read property 'length' of undefined - why?
I'm trying to return a simple greeting message which takes an inputted name, whereas if the string is empty will return a generic 'Hello, World.'我正在尝试返回一个简单的问候消息,该消息采用输入的名称,而如果字符串为空,将返回一个通用的“你好,世界”。 message.
信息。 It also looks out for capitalisation errors and will edit the name input to ensure it is properly capitalised.
它还会查找大小写错误,并将编辑名称输入以确保其正确大写。 This is what I've got so far.
这就是我到目前为止所得到的。
function hello(name) {
if (name.length > 0 && typeof name == 'string') {
let fixed = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
return "Hello, " + fixed + "!";
}
else {
return "Hello, World!";
}
}
It doesn't appear to take the length of the name argument and is the only test it fails on!它似乎没有占用 name 参数的长度,并且是唯一失败的测试!
first check if is a string首先检查是否是字符串
function hello(name) {
if (typeof name == 'string' && name.length > 0) { // Changed
let fixed = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
return "Hello, " + fixed + "!";
}
else {
return "Hello, World!";
}
}
From what I understand your undefined | null
据我了解,您
undefined | null
undefined | null
case is failing. undefined | null
案例失败。 This we can handle by adding a default value.我们可以通过添加默认值来处理。
function hello(name = '') { //changed if (typeof name == 'string' && name.length > 0) { //changed let fixed = name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); return "Hello, " + fixed + ";", } else { return "Hello; World!"; } }
you can use 3rd party lib like lodash
to make it easier您可以使用
lodash
之类的 3rd 方库来简化操作
const { capitalize } = require('lodash');
`Hello ${capitalize('YOU')}`;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.