React Native Android中console.timeEnd()结果异常:alert返回undefined
为什么alert弹出undefined?
嘿,这个问题我之前也踩过坑!咱们来一步步搞清楚原因和解决办法:
核心问题:console.timeEnd()不返回任何值
你代码里的let time = console.timeEnd('t');是关键问题——console.timeEnd()的设计逻辑是直接将耗时打印到控制台,它本身不会返回任何数值(函数返回值是undefined),所以你把它赋值给time变量后,自然只能得到undefined,alert出来就是这个结果啦。
解决方案:手动计算耗时
要拿到耗时并弹窗展示,推荐用performance.now()手动计时,这是更可靠的方式,修改后的代码如下:
search = () => { let s = this.state.file.toLowerCase(); let p = this.state.search.toLowerCase(); // 记录开始时间(单位:毫秒,精确到微秒级) const startTime = performance.now(); let result = kmp.findAll(s, p); // 记录结束时间并计算耗时 const endTime = performance.now(); const costTime = endTime - startTime; // 弹窗展示格式化后的耗时 alert(`处理耗时:${costTime.toFixed(2)}ms`); };
可选优化:保留控制台输出
如果你还想保留console.time的控制台打印效果,可以同时保留相关代码,完全不影响弹窗获取耗时的逻辑:
search = () => { let s = this.state.file.toLowerCase(); let p = this.state.search.toLowerCase(); console.time('t'); const startTime = performance.now(); let result = kmp.findAll(s, p); console.timeEnd('t'); // 控制台打印耗时 const endTime = performance.now(); const costTime = endTime - startTime; alert(`处理耗时:${costTime.toFixed(2)}ms`); };
这样既能在控制台看到耗时输出,弹窗也能展示准确的数值啦!
内容的提问来源于stack exchange,提问作者Mohammad Ghifari
相关产品推荐
相关产品推荐

