I'm trying to pass two arguments in a function that has String.prototype.slice(), but the console keeps on returning this error:
Uncaught TypeError: Cannot read property 'slice' of undefined".
Aren't the arguments supposed to be passed?
const testText = '<p style='color: red;'>This is a test</p>' const testParagraph = document.getElementById('test') const message = (paragraph, originText) => { let i = 0, text, isTag const speed = 50 text = originText.slice(0, ++i) if (text === originText) return paragraph.innerHTML = text const char = text.slice(-1) if (char === '<') isTag = true if (char === '>') isTag = false if (isTag) return message() setTimeout(message, speed) } message(testParagraph, testText)
<div id="test"></div>
There are two places where a recursive call of message
function may happen:
if (isTag) return message()
setTimeout(message, speed)
In both cases message
function is called without arguments. Due to this paragraph
are originText
parameters are associated with undefined
value. Then it tries to call .slice
on undefined
which raises the error.
You need to pass arguments to a recursive call, since it (like a regular function invocation) creates a new execution context with it's one lexical environment.
if (isTag) return message(arg1, arg2)
setTimeout(message.bind(null, arg1, arg2), speed)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.