在開發的時候,經常需要運算元據。需要將陣列中某些目標元素刪除時遇到了一些問題:
假設我們有一個人員陣列person,需要將元素裡面age>18的元素刪除
let person=[
{name:"lilei",age:"45"},
{name:"hanmeimei",age:"16"},
{name:"rose",age:"18"},
{name:"jack",age:"22"},
{name:"david",age:"25"},
{name:"bruce",age:"30"},
{name:"roby",age:"26"},
{name:"TMC",age:"11"},
{name:"lee",age:"40"},
]
複製程式碼
現在我們使用forEach方法迴圈然後刪除對應的目標元素
person.forEach((value,index)=>{
if(value.age>18){
person.splice(index,1)
}
})
複製程式碼
我們看看輸出結果是什麼:

經過查詢資料,可以通過以下方法來解決這個問題: 方法一:在每次執行splice方法之後都講當前迴圈的下標值減1,此方法在forEach方法中無效,至於具體原因我也不清楚,請大佬指教。使用for迴圈實現 for(var i=0;i<person.length;i++){ if(person[i].age>18){ person.splice(i--,1) } } 輸出結果:

方法二:使用for迴圈逆向遍歷.這種方法相當於每次執行splice方法的時候都將陣列的長度減1
for(var i=person.length-1;i>-1;i--){
if(person[i].age>18){
person.splice(i,1)
}
}
複製程式碼
輸出結果:

方法三:使用陣列的filter方法。filter()方法使用指定的函式測試所有元素,返回一個包含所有通過的元素新的陣列
var newPerson=person.filter((p)=>p.age<=18)
複製程式碼
輸出newPerson:


陣列按指定順序排序
let obj=[
{name:"test",age:18},
{name:"test1",age:20},
{name:"test2",age:25}
]
let arr=[25,18,20]
let result=[]
for(let i=0;i<arr.length;i++){
result=result.concat(obj.filter(a=>a.age==arr[i]))
}
複製程式碼
輸出結果:
