2013-03-07 123 views
0
if (sorted[i].Document === 'abc' || sorted[i].Document === 'xyz') { 
    delete sorted[i].Document; 
} 

當我嘗試刪除特定的兩個文檔時,它將被刪除,但下一次它會引發錯誤,說明文檔未定義。從數組中刪除特定值

var sorted = DocumentListData.Documents.sort(function (a, b) { 
    var nameA = a.Document.toLowerCase(), 
     nameB = b.Document.toLowerCase(); 

    return nameA.localeCompare(nameB); 
}); 

我整理文檔,然後遍歷它,然後試圖刪除它們abc and xyz的文件。

+0

會刪除屬性'Document',但不數組中的元素。 – Amberlamps 2013-03-07 15:45:32

回答

0

您試圖對不存在的屬性調用toLowerCase,因爲您剛刪除它們。在嘗試對它們執行方法之前檢查它們是否存在。

// i used empty string as the default, you can use whatever you want 
var nameA = a.Document ? a.Document.toLowerCase() : ''; 
var nameB = b.Document ? b.Document.toLowerCase() : ''; 

如果你想刪除的數組元素,而不僅僅是他們的Document特性,你應該使用splice代替delete

if (sorted[i].Document === 'abc' || sorted[i].Document === 'xyz') { 
    sorted.splice(i, 1); 
} 
+0

我正在嘗試刪除文檔屬性值。 – theJava 2013-03-07 16:29:42