如何根據以下javascript對象的courseID和endDate刪除一個項目?從Javascript對象中刪除單個對象
window.MyCheckedCourses = [
{ courseID: '123', endDate: '6/7/2010' },
{ courseID: '123', endDate: '3/9/2003' },
{ courseID: '456', endDate: '3/9/2003' }
];
如何根據以下javascript對象的courseID和endDate刪除一個項目?從Javascript對象中刪除單個對象
window.MyCheckedCourses = [
{ courseID: '123', endDate: '6/7/2010' },
{ courseID: '123', endDate: '3/9/2003' },
{ courseID: '456', endDate: '3/9/2003' }
];
迭代是必須的。您必須使用.splice()
刪除相應的項目,並使用break
for循環。
var i, id = '123', date = '6/7/2010';
for(var i = 0, il = MyCheckedCourses.length;i<il;i++) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;
}
}
你可以製作一個函數,並使用它的參數是這樣的;
function remove(id, date) {
for(var i = 0, il = MyCheckedCourses.length;i<il;i++) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
break;
}
}
}
// Example usage:
remove('123', '6/7/2010');
編輯後伊恩的comment:
我認爲您的收藏具有獨特的項目。如果沒有,你必須遍歷所有項目,你必須向後做,因爲如果你從數組中刪除一個元素,它的索引將會改變,迭代將無法正常工作。所以這個函數是一個更安全的版本。
function remove(id, date) {
for(var i = MyCheckedCourses.length - 1;i >= 0;i--) {
if(MyCheckedCourses[i].courseID == id && MyCheckedCourses[i].endDate == date) {
MyCheckedCourses.splice(i, 1);
}
}
}
// Example usage:
remove('123', '6/7/2010');
雖然'id'讓我想到「獨特」(我知道標題說「單個對象」,但是可能意味着在幾個地方有一個「單一對象」),如果可能存在多個匹配,那麼你必須向後(去掉「break」和「)循環 – Ian
你是對的Ian,我要更新我的答案。 –
可以使用拼接刪除數組中的元素:MyCheckedCourses.splice(index,length);
一個例子:
MyCheckedCourses=[0,1,2,3];
MyCheckedCourses.splice(1,1);
MyCheckedCourses
現在是:[0, 1, 3]
根據鍵值找到索引您可以使用:
// only returns the first found index
function findBy(arr,keys){
var i = 0,match,len;
for(i=0,len=arr.length;i<len;i++){
match=true;
for(key in keys){
if(arr[i][key]!==keys[key]){
match=false;
break
}
}
if(match===true){
return i;
}
}
return false;
}
var courses=[
{ courseID: '123', endDate: '6/7/2010' },
{ courseID: '123', endDate: '3/9/2003' },
{ courseID: '456', endDate: '3/9/2003' }
];
var index = findBy(courses,
{courseID:"123",
endDate:"3/9/2003"}
);
if(index!==false){
courses.splice(index,1);
}
console.log(courses);
這不是一個對象,它是對象的「數組」。 – mavili
'window.MyCheckedCourses'是一個數組,而不是一個jQuery對象。 –
jQuery在哪裏? –