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

时间:2021-04-08 17:12:54

标签: javascript string string-length

我试图返回一个简单的问候消息,它需要一个输入的名字,而如果字符串为空,将返回一个通用的“你好,世界!”信息。它还会查找大写错误,并编辑名称输入以确保正确大写。这是我到目前为止所得到的。

   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 参数的长度,并且是它失败的唯一测试!

3 个答案:

答案 0 :(得分:0)

首先检查是否是字符串

dict <- dictionary(
  structure(
    # this causes each ngram to be treated as a single "value"
    as.list(ngrams),
    # each dictionary key will be the unique token
    names = sapply(ngrams, function(x) strsplit(x, split = " ")[[1]][1], simplify = TRUE, USE.NAMES = FALSE)
  )
)

# convert the sequence to their keys
toks2 <- tokens_lookup(toks, dict, exclusive = FALSE, nested_scope = "dictionary", capkeys = FALSE)

print(toks2, max_ntoken = -1)
## Tokens consisting of 1 document.
## text1 :
##  [1] "this"       "will"       "analysis"   "should"     "remove"    
##  [6] "all"        "of"         "the"        "duplicated" "or"        
## [11] "repeated"   "words"      "and"        "return"     "only"      
## [16] "their"      "first"      "occurrence"

答案 1 :(得分:0)

据我所知,您的 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!";
  }
}

答案 2 :(得分:0)

你可以使用像 lodash 这样的 3rd 方库来让它更容易

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