打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
Uncaught TypeError: Cannot read properties of undefined (reading toString)
表白:黑白圣堂血天使,天剑鬼刀阿修罗。 
讲解对象:
/Uncaught TypeError: Cannot read properties of undefined (reading toString)
作者:融水公子 rsgz
===

js 出现的这个问题 百思不得其解,感觉很奇怪,因为数字转化为字符串 这么简单的逻辑不可能写错吧。


我甚至写了下面的逻辑进行测试了一下 发现toString()这个写法没问题 是能够正常的转换数字为字符串的

ye_num=7
ye = q('div.paging-box.tab-nav.page-up')[0]
    .querySelector('ul li:nth-last-child(2)')
    .querySelectorAll('a[title^="第"]')[0];
if (ye && ye.innerText.includes(ye_num.toString()+'/')) {
    console.log(1111)
}

但是神奇的一幕发生了
当我写成这样总是报错,很奇怪
function checkAndClick_a_dijiye(ye_num) {
  ye = q('div.paging-box.tab-nav.page-up')[0]
    .querySelector('ul li:nth-last-child(2)')
    .querySelectorAll('a[title^="第"]')[0];
  if (ye && ye.innerText.includes(ye_num.toString()+'/')) {
    delayedCode();
  } else {
    setTimeout(checkAndClick_a_dijiye, 2500); // 这里的时间间隔可以根据需要进行调整
  }
}

后来才知道,这里面传参的时候没有写全,应该要把ye_num参数传进去,否则就在函数里面出现了ye_num未定义的情况  这种情况下未定义的对象怎么可能使用toString()方法呢?百分百报错啊
setTimeout(checkAndClick_a_dijiye, 2500)

修改成这样就没问题了
function checkAndClick_a_dijiye(ye_num) {
  ye = q('div.paging-box.tab-nav.page-up')[0]
    .querySelector('ul li:nth-last-child(2)')
    .querySelectorAll('a[title^="第"]')[0];
  if (ye && ye.innerText.includes(ye_num.toString()+'/')) {
    delayedCode();
  } else {
    setTimeout(checkAndClick_a_dijiye(ye_num), 2500); // 这里的时间间隔可以根据需要进行调整
  }
}

这么做会解决当前的问题 但是会制造一个新的问题,我们不能再setTimeout里面显示的传参,需要写成匿名函数的形式才可以,否则setTimeout 会立即执行
function checkAndClick_a_dijiye(ye_num) {
  ye = q('div.paging-box.tab-nav.page-up')[0]
    .querySelector('ul li:nth-last-child(2)')
    .querySelectorAll('a[title^="第"]')[0];
  if (ye && ye.innerText.includes(ye_num.toString()+'/')) {
    delayedCode();
  } else {
    setTimeout(() => checkAndClick_a_dijiye(ye_num), 2500);
  }
}
改成这样的写法就没问题了
setTimeout(() => checkAndClick_a_dijiye(ye_num), 2500);
=== 
公众号:不浪仙人
谢谢大家的支持!可以点击我的头像,进入我的空间浏览更多文章呢。建议大家360doc[www.360doc.com]注册一个账号登录,里面真的有很多优秀的文章,欢迎大家的到来。
---
';
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
自1000多个项目的十大JavaScript错误(以及如何避免)
10 个最常见的 JavaScript 错误(以及如何避免它们)- 来自 Rollbar 1000 ...
成功解决TypeError int object is not iterable
Uncaught TypeError: Cannot read property 'opera' of undefined
JavaScript异常报错处理:Uncaught TypeError: xxx is not a function
如何禁止JavaScript对象重写? | Fundebug博客
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服