javascript - 无法在模板文字中调用函数
问题描述
你好 StackOverflow 英雄,
我有一个业余问题,为什么我不能在模板文字中调用这个函数。代码返回未定义,控制台中没有任何错误。我似乎看不出我做错了什么,我错过了退货声明吗?
function startCountdown(seconds) {
let counter = seconds;
const interval = setInterval(() => {
console.log(counter);
counter--;
if (counter < 0) {
clearInterval(interval);
}
}, 1000);
}
document.body.innerHTML = `<p>Quick! Click to stop the page from self destructing. You have ${startCountdown(
5
)} seconds.</p>`;
谢谢!
解决方案
当您不从函数中返回任何内容时,将隐式undefined
返回。因此你会得到You have undefined seconds.</p>
你必须从你的函数返回一个值。
即使您从函数返回一个值,您也会得到与作为参数传递的相同的值,因为setInterval
本质上是异步的,这意味着在时间间隔开始和结束时,您的函数已经返回了该值。
function startCountdown(seconds) {
let counter = seconds;
const interval = setInterval(() => {
console.log(counter);
counter--;
if (counter < 0) {
clearInterval(interval);
}
}, 1000);
return counter;
}
You have 5 seconds.</p>
如果你5
作为参数传递给你的函数,你会得到。
推荐阅读
- javascript - 使用 Javascript 检查是否发生 CORS 错误
- flutter - 根据 Flutter 中选定的类别为小部件元素分配不同的颜色
- python - 如何在Python中的函数调用中正确缩进多行参数列表
- arrays - char 数组是否比 C 中的 char 指针更有效?
- php - PHP Curl 忽略 META REFRESH 重定向上的 CURLOPT_COOKIEFILE
- android - 使用 PreferencesDataStore 将主题设置为活动
- macros - 为什么默认情况下不急切地扩展 lisp 宏?
- python - 如何在给它另一个任务的同时修复kivy没有响应
- c# - signInManager.IsSignedIn 返回 false 但调用了 SignInAsync
- xquery - 如何在marklogic中使用xquery返回除元素之外的现有文档