Receiving TypeError: Cannot read property 'length' of undefined - why?

Receiving TypeError: Cannot read property 'length' of undefined - why?

我正在尝试 return 一个简单的问候消息,它采用输入的名称,而如果字符串为空,则 return 将是一个通用的 'Hello, World!' 消息。它还会查找大写错误并编辑名称输入以确保其大写正确。这就是我到目前为止所得到的。

   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!";
  }
}

它似乎没有采用 name 参数的长度,并且是它失败的唯一测试!

首先检查是否是一个字符串

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!";
  }
}

据我了解,您的 undefined | null 案例失败了。 我们可以通过添加默认值来处理。

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!";
  }
}

您可以使用像 lodash 这样的第 3 方库来简化操作

const { capitalize } = require('lodash');
`Hello ${capitalize('YOU')}`;