JavaScript — неперехваченная ошибка типа: общий тип [totypeIndex] не определен

#javascript #html #css #undefined

#javascript #HTML #css #не определено

Вопрос:

Я следил за учебным пособием, завершил учебное пособие и создал проект, но через некоторое время мой JS показывает ошибку Uncaught TypeError: totype[totypeIndex] is undefined , когда я пытаюсь сначала зарегистрировать тип totype[totypeIndex] , который он показал String , а затем через некоторое время он показал undefined .

Мой код:

 const typedSpan = document.querySelector(".typed") // Storing the Span of HTML of Class 'typed' for changing the text
const totype = ["Fun", "Hard", "Love"] // Array in which all of the words which have to be typed are stored

const delayTyping_char = 200; // 200ms will be waited before next Character of the Text is typed
const delayErasing_text = 150; // 100ms will be waited before removing the next character
const delayTyping_text = 3000; // 2500ms will be waited before everything is erased amp; next text is typed

let totypeIndex = 0; // Index of The text which is being typed
let charIndex = 0; // Index of The Character which is being typed


function typeText() {
  if (charIndex < totype[totypeIndex].length) {
    typedSpan.textContent  = totype[totypeIndex].charAt(charIndex); // Value of The Span in HTML is = the Character at the index of charIndex of the Text which is being typed
    charIndex  ; // Adding 1 to charIndex
    setTimeout(typeText, delayTyping_char); // Calling typeText Until the charIndex is greater than the lenght of the Text which is being typed
  } else {
    setTimeout(eraseText, delayTyping_text); // if charIndex is Greater than lenght of the text which is being type then after the time setted (delayTyping_text) erase function will be called
  }
}

function eraseText() {
  if (charIndex > 0) {
    typedSpan.textContent = totype[totypeIndex].substring(0, charIndex - 1); // substring(0, charIndex-1) here charIndex-1 is saying to select the text leaving one of last text behind
    charIndex = charIndex - 1; // subtracting 1 from charIndex
    setTimeout(eraseText, delayErasing_text); // Will call eraseText() Function until the charIndex is not equal to 0
  } else {
    totypeIndex  ; // If everything is erased then the totypeIndex will be increased and next text in Array (totype) will be typed

    if (totypeIndex > totype.length) // If totypeIndex is equal to or greater than the number of text to be typed then
      totypeIndex = 0; // totypeIndex will be 0 so that we can start from the first text in the array (toType) and
    setTimeout(typeText, delayTyping_text); // after some delay presetted (delayTyping_text) typeText() Function is called
  }
}

window.onload = function() {
  setTimeout(typeText, delayTyping_text);
} // typText() Function is called when everything is loaded 
 * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #111111;
  font-family: monospace;
  color: #ffffff;
  text-align: center;
}

.wrapper {
  height: 100vh;
  width: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

.effect-wrapper {
  text-align: center;
  font-weight: normal;
}

.typed {
  font-weight: bold;
  color: #00bdff;
}

.cursor {
  display: inline-block;
  background-color: #b0ff95;
  animation: blinker 800ms infinite;
}

.cursor.typing-true {
  animation: none;
}

@keyframes blinker {
  0% {
    background-color: #b0ff95;
  }
  50% {
    background-color: transparent;
  }
  100% {
    background-color: #b0ff95;
  }
} 
 <div class="wrapper">
  <!-- Wrapper Start -->
  <h1 class="effect-wrapper">Coding is <span class="typed"></span> <span class="cursor">amp;nbsp;</span></h1>
</div>
<!-- Wrapper End --> 

Пожалуйста, скажите мне, в чем была ошибка и как мне ее исправить?

Заранее спасибо

Комментарии:

1. Отладка….. console.log(totypeIndex, totype[totypeIndex])

2. Внутри eraseText функции измените totypeIndex > totype.length на totypeIndex >= totype.length . Значение totypeIndex должно быть сброшено на ноль, если его значение больше или равно длине totype массива

Ответ №1:

здесь опечатка

 if (totypeIndex > totype.length) // If totypeIndex is equal to or greater than the number of text to be typed then
 

вы должны установить для этого оператора значение выше или равно, поэтому используйте >= вместо >

 const typedSpan = document.querySelector(".typed") // Storing the Span of HTML of Class 'typed' for changing the text
const totype = ["Fun", "Hard", "Love"] // Array in which all of the words which have to be typed are stored

const delayTyping_char = 200; // 200ms will be waited before next Character of the Text is typed
const delayErasing_text = 150; // 100ms will be waited before removing the next character
const delayTyping_text = 3000; // 2500ms will be waited before everything is erased amp; next text is typed

let totypeIndex = 0; // Index of The text which is being typed
let charIndex = 0; // Index of The Character which is being typed


function typeText() {
  if (charIndex < totype[totypeIndex].length) {
    typedSpan.textContent  = totype[totypeIndex].charAt(charIndex); // Value of The Span in HTML is = the Character at the index of charIndex of the Text which is being typed
    charIndex  ; // Adding 1 to charIndex
    setTimeout(typeText, delayTyping_char); // Calling typeText Until the charIndex is greater than the lenght of the Text which is being typed
  } else {
    setTimeout(eraseText, delayTyping_text); // if charIndex is Greater than lenght of the text which is being type then after the time setted (delayTyping_text) erase function will be called
  }
}

function eraseText() {
  if (charIndex > 0) {
    typedSpan.textContent = totype[totypeIndex].substring(0, charIndex - 1); // substring(0, charIndex-1) here charIndex-1 is saying to select the text leaving one of last text behind
    charIndex = charIndex - 1; // subtracting 1 from charIndex
    setTimeout(eraseText, delayErasing_text); // Will call eraseText() Function until the charIndex is not equal to 0
  } else {
    totypeIndex  ; // If everything is erased then the totypeIndex will be increased and next text in Array (totype) will be typed

    if (totypeIndex >= totype.length) // If totypeIndex is equal to or greater than the number of text to be typed then
      totypeIndex = 0; // totypeIndex will be 0 so that we can start from the first text in the array (toType) and
    setTimeout(typeText, delayTyping_text); // after some delay presetted (delayTyping_text) typeText() Function is called
  }
}

window.onload = function() {
  setTimeout(typeText, delayTyping_text);
} // typText() Function is called when everything is loaded 
 * {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  background-color: #111111;
  font-family: monospace;
  color: #ffffff;
  text-align: center;
}

.wrapper {
  height: 100vh;
  width: auto;
  display: flex;
  justify-content: center;
  align-items: center;
}

.effect-wrapper {
  text-align: center;
  font-weight: normal;
}

.typed {
  font-weight: bold;
  color: #00bdff;
}

.cursor {
  display: inline-block;
  background-color: #b0ff95;
  animation: blinker 800ms infinite;
}

.cursor.typing-true {
  animation: none;
}

@keyframes blinker {
  0% {
    background-color: #b0ff95;
  }
  50% {
    background-color: transparent;
  }
  100% {
    background-color: #b0ff95;
  }
} 
 <div class="wrapper">
  <!-- Wrapper Start -->
  <h1 class="effect-wrapper">Coding is <span class="typed"></span> <span class="cursor">amp;nbsp;</span></h1>
</div>
<!-- Wrapper End --> 

Комментарии:

1. поскольку этот оператор устанавливает для totypeindex значение 0, если оно превышает длину totype, до тех пор, пока ваш totypeindex не будет превышать элементы массива, он не будет возвращаться в соответствии с инструкцией, поэтому в этом случае totypeindex остановится на последнем элементе вашего массива, поэтому текстфункция erase больше не найдет текст для удаления в цикле, вот почему