尽管这段代码可以正常工作,即打印文本,但第32行出现控制台错误,内容为:“未定义不是对象(评估'dataText [i] .length')”

有什么想法吗?

document.addEventListener('DOMContentLoaded',function(event){
  // array with texts to type in typewriter
  var dataText = [ "Hi", "it's Acephala", "Shipping is free for you today",];

  // type one text in the typwriter
  // keeps calling itself until the text is finished
  function typeWriter(text, i, fnCallback) {
    // chekc if text isn't finished yet
    if (i < (text.length)) {
      // add next character to h1
     document.querySelector("h1animation").innerHTML = text.substring(0, i+1) +'<spananimation aria-hidden="true"></spananimation>';

      // wait for a while and call this function again for next character || BK: Speed of text writing
      setTimeout(function() {
        typeWriter(text, i + 1, fnCallback)
      }, 100);
    }
    // text finished, call callback if there is a callback function
    else if (typeof fnCallback == 'function') {
      // call callback after timeout
      setTimeout(fnCallback, 700);
    }
  }
  // start a typewriter animation for a text in the dataText array
   function StartTextAnimation(i) {
     if (typeof dataText[i] == 'undefined'){
        setTimeout(function() {
          StartTextAnimation(0);
        }, 20000);
     }
     // check if dataText[i] exists
    if (i < dataText[i].length) {
      // text exists! start typewriter animation
     typeWriter(dataText[i], 0, function(){
       // after callback (and whole text has been animated), start next text
       StartTextAnimation(i + 1);
     });
    }
  }
  // start the text animation
  StartTextAnimation(0);
});

最佳答案

您的代码可以:

if (typeof dataText[i] == 'undefined'){
  ...
}
if (i < dataText[i].length) {
  ...
}


这意味着即使i < dataText[i].lengthdataText[i],也会评估undefined。在第一个return块的末尾添加if语句,或使用else if (i < dataText[i].length) {



除此之外,我相信检查实际上应该是i < dataText.length。比较dataText[i]i的长度似乎不合理。

如果您进行更改,则不必先提及更改。

但是,在那种情况下,我宁愿在回调内部进行检查,这意味着StartTextAnimation始终会收到有效的索引:

function StartTextAnimation(i) {
  typeWriter(dataText[i], 0, function(){
    // after callback (and whole text has been animated), start next text
    if (i === dataText.length - 1) {
      setTimeout(function() {
        StartTextAnimation(0);
      }, 20000);
    } else {
      StartTextAnimation(i + 1);
    }
  });
}

关于javascript - JS错误:“未定义不是对象(正在评估'dataText [i] .length']”),我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53218008/

10-10 05:41