2010-07-16 40 views
0

我一直在使用Javascript,最近我一直困擾着一個我無法解決的錯誤。Javascript會拋出一個「未定義」錯誤

Firefox控制檯會拋出「info [last] is undefined」錯誤,我不知道是什麼導致了這種情況。這裏是代碼,引發麻煩的線是7號:

$("textarea").each(function() { 
var id = $(this).parents("div.article").attr('id').split('_')[1], 
    kind = $(this).attr("class"), 
    text = $(this).val(), 
    last = info.length-1; 

    if(last !== 0) { 

     if(info[last].id == id) { 
      info[last].info.push([kind, text]); 

     } 

    } else { 

     object = { 
      id: id, 
      info: [[kind, text]] 
     }; 

    } 

    info.push(object); 
}); 

希望你們可以幫我弄明白。

+0

'info'中發生了什麼,其中有零個元素? 「信息」在哪裏定義? – 2010-07-16 17:27:06

+0

沒看過!==以前,你確定它有效嗎? (與!=相比) 編輯:R. Hill是對的,如果info有0個元素,那麼你做一個info [-1] .id == id ... 更改最後!==檢查最後> 0 – Steffen 2010-07-16 17:28:39

+0

Steffen:!==是嚴格的!=,它不會進行類型轉換。 – Jake 2010-07-16 17:36:34

回答

2

如何:

$("textarea").each(function() { 
var id = $(this).parents("div.article").attr('id').split('_')[1], 
    kind = $(this).attr("class"), 
    text = $(this).val(), 
    last = info.length-1; 

    if(last >= 0) { 
     //Check the index exists before accessing it - incase its null or similiar.. 
     //Strictly speaking, we should test for the properties before we access them also. 
     if(info[last]) { 
     if(info[last].id == id) { 
      info[last].info.push([kind, text]); 

     } 
     } 

    } else { 

     object = { 
      id: id, 
      info: [[kind, text]] 
     }; 
     info.push(object); //Also move this up. 

    } 


}); 

我動了幾周圍的事物,並改變了檢驗有效的「最後一個」。否則,我還添加了一個if,如果在嘗試訪問其屬性之前檢查數組中該點是否存在該對象。

1

如果info爲空,則last將爲-1

更改if

if(last !== -1) { 

而且,你可能要移動

info.push(object); 

else內。

+0

謝謝,它工作得很好:) – 2010-07-16 17:41:11

+1

然後,你應該通過點擊鏤空檢查來接受這個答案。 – SLaks 2010-07-16 17:43:17

相關問題