早睡早起,方能养生
Sleep early rise early, way to keep healthy

Uncaught TypeError: Cannot read property 'length' of null

super
2021-03-29 12:34
views 3656

Javascript报错 Uncaught TypeError: Cannot read property 'length' of null

 

报此错误是因为使用了 xx.length 判断了数组的长度,而数组为空,报错

 

 

正确的做法是,在我们拿到后台返回的数据后,需判断是否为null

 

$.post("rongsp.com", {param: 'param'}, function(data) {
	if (data.list1 != null) {
		if (data.list1.length > 0) {
			$.each(data.list1, function(key, value) {
				// do something...
			})
		}
	}

	if (data.list2 != null) {
		if (data.list2.length > 0) {
			$.each(data.list2, function(key, value) {
				// do something...
			})
		}
	}
}, 'json')

 

以上面这个为例,如果我们list1为null,而list1没有做是否为null判断,list2将无法正常运行,这可是非常致命的!!!

 

 

https://www.javascript.com/learn/arrays

 



分享
0 条讨论
top