从数组中删除特定值
问题描述:
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
的文件。
答
您试图对不存在的属性调用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
会删除属性'Document',但不数组中的元素。 – Amberlamps 2013-03-07 15:45:32