我怎么能做一个无限循环显示项目从一个数组的字母一个字母?



我想创建一个无限循环,从数组中逐个字母和项显示msg。有人能帮忙吗?

let textArr = ['first', 'second', 'third'];
let i = 0;
let j = 0;
function spell() {
if (j = 0) {
clear();
}
setTimeout(function() {
show();
j + 0;
if (j = textArr[i].length) {
j = 0;
i++;
}
if (i = textArr.length) {
i = 0;
j = 0;
}
spell();
}, 1000);
}
// clear the spelling
function clear() {
document.querySelector('#targ').innerHTML = '';
}
// show the spelling
function show() {
document.querySelector('#targ').innerHTML += textArr[i][j];
}
addEventListener('load', spell());
<center id="targ">
</centre>

将您的数组join变为字符串,并遍历该字符串。

const arr = ['first', 'second', 'third'];
const targ = document.querySelector('#targ');
// Pass the array into the function
function spell(arr) {
// `join` it up
const str = arr.join(' ');
// Have an inner function that you call
// from the setTimeout initialising the index to 0
function loop(i = 0) {
// If the index is less than the string length
// update the textContent of the element, and
// increase the index
if (i < str.length) {
targ.textContent += str[i];
++i;
// Otherwise empty the textContent,
// and set the index to zero
} else {
targ.textContent = '';
i = 0;
}
// Then call the loop function again with
// the updated index as an argument
setTimeout(loop, 200, i);
}

loop();
}
spell(arr);
<div id="targ"></div>

let textarr = ['first', 'second', 'third'];
let i = 0
let j = 0
let str = textarr[0]
setInterval(function() {
i += 1
console.log( str.slice(0,i))
if(i == textarr[j%3].length){
i = 0
j += 1
str = textarr[j%3]
}
}, 1000);

相关内容

  • 没有找到相关文章