[英]Why can't I remove elements from the array?
這個 function 應該刪除小於 1 和大於 4 的元素,但它沒有。 數組還是一樣的。
let arr = [5, 3, 8, 1]; function filterRangeInPlace(arr, a, b) { arr.forEach((item, index) => { if (a > item && b < item) { arr.splice(index, 1); }; }); }; filterRangeInPlace(arr, 1, 4); console.log(arr);
怎么了?
什么時候單個項目既小於 1 又大於 4? 如果要刪除小於 1或大於 4 的項,則需要執行以下操作:
if (a > item || b < item)
你在調用 function 時反轉了 arguments。你應該這樣做
filterRangeInPlace(arr, 4, 1)
您基本上是將項目保持在給定范圍之間,而不是刪除項目 go 以保持項目這將返回相同的也使用filter
function 它基本上遍歷數組,就像foreach
里面有兩個參數 item 和 index 唯一的區別是過濾器在您時保留值如果返回 false,則返回 true 或忽略
您可以在此處查看有關過濾器的更多信息
let arr = [5, 3, 8, 1]; function filterRangeInPlace(arr, a, b) { return arr.filter(each=>{ return each > a && each < b }) }; arr = filterRangeInPlace(arr, 1, 4); console.log(arr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.