简体   繁体   English

Javascript'未捕获的TypeError:无法读取未定义'的属性'blah'

[英]Javascript 'Uncaught TypeError: Cannot read property 'blah' of undefined '

I'm trying to test if an array element is undefined: 我正在尝试测试数组元素是否未定义:

  if(typeof selected[i].facet != 'undefined')
  {
       //do stuff
  }

gives me 给我

Javascript 'Uncaught TypeError: Cannot read property 'facet' of undefined '

您必须同时测试数组索引和属性:

if (selected[i] && selected[i].facet !== undefined) { // ...
if((selected[i]) && (selected[i].facet != undefined))
  {
       //do stuff
  }

You should just do your loop properly 您应该正确地执行循环

for (var i = 0, len = selected.length; i < len; ++i) {
    //selected[i] will always be a valid index in the array
}

Should it be the case that selected[i] is a valid index in the array, but undefined regardless, then you don't semantically need an array but a dictionary with integers as keys. 如果selected[i]是数组中的有效索引,但是无论如何都undefined ,那么在语义上就不需要数组,而需要一个以整数作为键的字典。 In that case, you can loop through it with for( var key in map ) . 在这种情况下,您可以使用for( var key in map )遍历它。 Aim to fix the source of errors instead of fighting the symptoms. 旨在修复错误的来源,而不是消除症状。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 未捕获的TypeError:无法读取未定义的“ Javascript”的属性“ 0” - Uncaught TypeError: Cannot read property '0' of undefined “Javascript” Uncaught TypeError:无法读取未定义的属性-javascript - Uncaught TypeError: Cannot read property of undefined - javascript Javascript Uncaught TypeError:无法读取未定义的属性“0” - Javascript Uncaught TypeError: Cannot read property '0' of undefined Javascript Uncaught TypeError:无法读取未定义的属性 - Javascript Uncaught TypeError: Cannot read property of undefined Javascript问题-未捕获的TypeError:无法读取未定义的属性&#39;x&#39; - Javascript Issue - Uncaught TypeError: Cannot read property 'x' of undefined 未捕获的TypeError:无法读取未定义的属性&#39;getBarCode&#39;(JavaScript) - Uncaught TypeError: Cannot read property 'getBarCode' of undefined (JavaScript) 未捕获的TypeError:无法读取未定义JavaScript的属性&#39;toString&#39; - Uncaught TypeError: Cannot read property 'toString' of undefined JavaScript Javascript错误:未捕获的TypeError:无法读取未定义的属性“ branchei” - Javascript error:Uncaught TypeError: Cannot read property 'branchei' of undefined Javascript和Jquery:未捕获的TypeError:无法读取未定义的属性&#39;length&#39; - Javascript and Jquery: Uncaught TypeError: Cannot read property 'length' of undefined 在JavaScript上获取“未捕获的TypeError:无法读取未定义的属性&#39;top&#39;” - Getting “Uncaught TypeError: Cannot read property 'top' of undefined” on javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM