简体   繁体   English

接收类型错误:无法读取未定义的属性“长度” - 为什么?

[英]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.

相关问题 为什么在定义的数组上收到“ ERROR TypeError:无法读取未定义的属性'length'的信息”? - Why am I receiving “ERROR TypeError: Cannot read property 'length' of undefined” on a defined array? 为什么我收到 TypeError:无法读取未定义的属性“执行” - Why am I receiving TypeError: cannot read property 'execute' of undefined 为什么我收到“ TypeError:无法读取未定义的属性” length” - Why am I getting 'TypeError: Cannot read property 'length' of undefined' 未捕获的TypeError:无法读取未定义的属性“长度” - Uncaught TypeError: Cannot read property 'length' of undefined TypeError无法读取未定义的属性“ length”-角度4 - TypeError cannot read property “length” of undefined - angular 4 opencv-TypeError:无法读取未定义的属性“长度” - opencv - TypeError: Cannot read property 'length' of undefined 未捕获的TypeError:无法读取未定义的属性“ length” - Uncaught TypeError: Cannot read property 'length' of undefined UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“长度” - UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'length' of undefined 未捕获的TypeError:无法读取未定义的属性“ length” - Uncaught TypeError: Cannot read property 'length' of undefined 开玩笑:TypeError:无法读取未定义的属性“长度” - Jest : TypeError: Cannot read property 'length' of undefined
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM