js中Uncaught TypeError: Cannot read property 'substr' of undefined问题分析
来源:互联网 发布:淘宝网女裤 编辑:程序博客网 时间:2024/06/03 22:07
博客已经迁移到http://www.cnblogs.com/sundjly/
在写的js中测试时遇到了Uncaught TypeError: Cannot read property ‘substr’ of undefined的问题,js关键代码为:
var Img = data[i].technician.portrait;//后台接收到的图片src的地址 //alert(typeof Img); if (Img!= '' || Img != undefined) { Img = SYS + Img.substr(1); //实现image的src的拼接 } else { Img = '--'; }
其中是if在判断时出了问题,因为从后台传输过来数据为
Img=undefined;(存在technician这个对象不存在portrait属性)
Img != undefined这样的判断是无效的。因此进入了条件为true的方法:
Img = SYS + Img.substr(1); Img不是对象,调用substr()方法就会出现问题
查阅一下资料才发现在判断是否为undefined应该用typeof 不能直接判断
代码改为:
var Img = arr[i].technician.portrait; if (typeof Img != "undefined") { Img = SYS + Img.substr(1); } else { Img = ''; }
不过在谷歌测试发现写成if(Img == undefined)也是能编译成功的
不过为了避免后台没有传值过来,可以进一步优化代码:
var Img = arr[i].technician.portrait||'--';//避免传过来Img为undefined或者null导致的编译错误 Img = SYS + Img.substr(1);
阅读全文
0 0
- js中Uncaught TypeError: Cannot read property 'substr' of undefined问题分析
- background.js Uncaught TypeError: Cannot read property 'xxx' of undefined
- Extjs4---Uncaught TypeError: Cannot read property ‘items’ of undefined
- 【StackFlow】Uncaught TypeError: Cannot read property 'pageCount' of undefined
- Ckeditor: Uncaught TypeError: Cannot read property 'keyCode' of undefined 解决方法
- Uncaught TypeError: Cannot read property 'msie' of undefined问题解决方案
- Uncaught TypeError: Cannot read property 'options' of undefined 错误
- Uncaught TypeError: Cannot read property 'length' of undefined
- 错误:Uncaught TypeError: Cannot read property 'WebSocket' of undefined
- Uncaught TypeError: Cannot read property 'value' of undefined
- Uncaught TypeError: Cannot read property 'plugin' of undefined
- react Uncaught TypeError: Cannot read property 'title' of undefined
- Uncaught TypeError: Cannot read property 'width' of undefined
- Uncaught TypeError: Cannot read property 'substring' of undefined
- Uncaught TypeError: Cannot read property 'PRINT_INIT' of undefined user:100
- Uncaught TypeError: Cannot read property 'substring' of undefined
- extjs4:Uncaught TypeError: Cannot read property 'processed' of undefined
- Datatables 之Uncaught TypeError: Cannot read property 'mData' of undefined
- 一个分布式服务器集群架构方案
- ADXL345中断的初始化设置
- Leetcode 213. House Robber II
- 51Nod 旋转字符串
- WebService到底是什么?
- js中Uncaught TypeError: Cannot read property 'substr' of undefined问题分析
- Java或.NET该怎么选择?
- Codeforces Round #422 (Div. 2) C. Hacker, pack your bags!
- eval
- centos6.5下安全架设FTP服务器
- JAVA多线程实现的三种方式
- 堆优化dijkstra bzoj2143飞飞侠
- 1012. The Best Rank (25)
- 前端构建工具-fis3使用入门