Javascript 避免无法读取的属性。。。未定义

Javascript 避免无法读取的属性。。。未定义,javascript,jquery,Javascript,Jquery,我使用此函数将title attr附加到表的每个tr。表的内容来自数组。那很好。但我还有一个函数,可以手动将行添加到表中。对于这些行,我得到一个异常。非常清楚,因为它们不在数组中。但我怎样才能避免这些例外呢?我不需要为这些行添加标题 它说: 无法读取未定义(…)的属性“dictCanon” 函数postBody(){ //为tr添加标题 var trs=$table.find('tbody').children(); 对于(变量i=0;i

我使用此函数将title attr附加到表的每个
tr
。表的内容来自数组。那很好。但我还有一个函数,可以手动将行添加到表中。对于这些行,我得到一个异常。非常清楚,因为它们不在数组中。但我怎样才能避免这些例外呢?我不需要为这些行添加标题

它说:

无法读取未定义(…)的属性“dictCanon”

函数postBody(){
//为tr添加标题
var trs=$table.find('tbody').children();
对于(变量i=0;i
此表达式触发错误“无法读取未定义的属性'dictCanon'”:

diagnosis[index].additionalParameters.dictCanon
…这意味着您在
诊断
中有没有
附加参数
属性的条目。您试图保护代码不受该错误的影响,但使用了错误的布尔运算符。使用
&&
而不是
|
,并且不要将
null
放在引号中。我还建议调整
for
循环中的条件,以确保在
诊断中有必要的条目:

function postBody() {
    // add title to tr
    var trs = $table.find('tbody').children();
    for (var i = 0; i < trs.length && i < diagnosis.length; i++) {
        $(trs[i]).mouseover(function(e) {
            var index = $(e.currentTarget).data('index'); // use `var`
            var d = diagnosis[index].additionalParameters // parentheses not needed
            console.log('d', d);
            dt = $(e.currentTarget).parent().parent().find('thead').find('th')
                                   .eq(index).data(); // you have `index`, use it
            //console.log(dictCanon);
            if (d !== undefined && d !== null) { // <--- changed!
                 var dictCanon = d.dictCanon; // <-- you have `d`, use it
                 var icd = d.icd; // <-- idem
                 $(this).attr('title',icd + ' ' + dictCanon);
             }
        });                
    };
};
函数postBody(){
//为tr添加标题
var trs=$table.find('tbody').children();
对于(变量i=0;i如果(d!==undefined&&d!==null){//您能发布错误消息吗?通常它会说“无法读取undefined的属性”当试图找出错误发生的确切位置时,这会很有帮助。或者,您可以检查行号,并告诉我们要查看哪一行。什么是
diagnosis
?它没有定义。另外
index
@Michelem,
index
在事件处理程序中检索,并与
i
的值对应创建事件处理程序时,它会显示“无法读取未定义(…)的属性'dictCanon'”,这意味着您的数组足够大,但并非所有条目都具有
additionalParameters
属性。因此,请展示您如何管理
diagnosis
数组。谢谢您,您救了我一天!
function postBody() {
    // add title to tr
    var trs = $table.find('tbody').children();
    for (var i = 0; i < trs.length && i < diagnosis.length; i++) {
        $(trs[i]).mouseover(function(e) {
            var index = $(e.currentTarget).data('index'); // use `var`
            var d = diagnosis[index].additionalParameters // parentheses not needed
            console.log('d', d);
            dt = $(e.currentTarget).parent().parent().find('thead').find('th')
                                   .eq(index).data(); // you have `index`, use it
            //console.log(dictCanon);
            if (d !== undefined && d !== null) { // <--- changed!
                 var dictCanon = d.dictCanon; // <-- you have `d`, use it
                 var icd = d.icd; // <-- idem
                 $(this).attr('title',icd + ' ' + dictCanon);
             }
        });                
    };
};