JavaScript逐字显示文本功能封装为函数时报.split不是函数如何解决
逐字显示功能封装报错原因及修复方案
报错触发原因
- 参数传递逻辑错误。初始调用
frameLooper(dialog('This is a test'))时,dialog已经将输入字符串转为数组返回,你将这个数组作为参数传入frameLooper的text形参,随后frameLooper又把该数组传给dialog(text),而dialog内部会对入参执行.split('')操作,数组本身不存在split方法,因此直接抛出你遇到的报错。 - 循环逻辑存在缺陷。你每次调用
frameLooper都会重新调用dialog生成全新的字符数组,哪怕解决了split报错,也会每次循环都拿到完整的新数组,永远只会输出第一个字符,无法完成全文展示。同时setTimeout使用字符串形式'frameLooper()'调用,执行时不会传入任何参数,会进一步触发二次报错。
修复后的可运行代码
你可以直接把逻辑封装为统一的调用函数,用闭包存储处理状态即可:
const typeText = (inputText, speed = 30) => { const textArray = inputText.split('') const target = document.querySelector('#text') // 展示前清空原有内容,可按需保留/删除 target.innerHTML = '' let loopTimer const frameLooper = () => { if (textArray.length > 0) { target.innerHTML += textArray.shift() loopTimer = setTimeout(frameLooper, speed) } else { clearTimeout(loopTimer) } } frameLooper() } // 调用示例:直接传入要显示的文本即可 typeText('This is a test')
如果需要保留你原来的dialog拆分逻辑,也可以调整为如下写法:
const dialog = (text) => text.split('') let loopTimer // 把数组提到循环外部存储,不要每次循环重新生成 let textArray const target = document.querySelector('#text') const frameLooper = () => { if (textArray.length > 0) { target.innerHTML += textArray.shift() loopTimer = setTimeout(frameLooper, 30) } else { clearTimeout(loopTimer) } } // 调用时先初始化数组,再启动循环 textArray = dialog('This is a test') // 启动前清空原有内容 target.innerHTML = '' frameLooper()
内容的提问来源于stack exchange,提问作者Asanyth
相关产品推荐
相关产品推荐

