返回未定义的 JavaScript 字符串长度

javascript string length returning undefined

本文关键字:字符串 JavaScript 未定义 返回      更新时间:2023-09-26

我似乎无法从表单文本字段中的值获取字符串长度这是我函数的代码,它传递文本字段名称的参数

  function validate(thing)
  {
  var location = document.getElementById(thing);
  var cardst = location.value;
  window.alert (cardst);
  cardst = String(cardst);
  window.alert (cardst.lenght);

第一个警报有效,它会提醒我在文本字段中键入的任何内容,但第二个警报始终未定义。如您所见,我确实将其转换为字符串,但我没有得到定义。一个想法??

那是因为你拼错了length :-)

请改用这个:

cardst.length;   // <- 'th', not 'ht'

您有语法错误。是长度不是长度

   function validate(thing)
  {
  var location = document.getElementById(thing);
  var cardst = location.value;
  window.alert (cardst);
  cardst = String(cardst);
  window.alert (cardst.lenght);
                           ^ /*should read window.alert(cardst.length)*/