JS错误:“未定义不是对象(正在评估'dataText [i] .length')”

时间:2018-11-09 00:09:43

标签: javascript

尽管这段代码可以按预期工作,即打印文本,但第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);
});

1 个答案:

答案 0 :(得分:2)

您的代码可以:

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);
    }
  });
}