📘arr.filter()
JS ⟩ object ⟩ built-in ⟩ array ⟩ method ⟩ .filter()
⭐️ 注意:array.filter() 會自動略過陣列中的「洞」❗️
replit ⟩ array ⟩ remove
const arr = [ 0, 1, '', , false, undefined, null, , , NaN];
// ⭐ 1. Remove all `undefined` (and "holes")
arr.filter(x => x !== undefined ); // [ 0, 1, '', false, null , NaN ]
// ⭐ 2. Remove all "nullish" values (and "holes")
// ✅ undefined == null, ✅ null == null
arr.filter(x => x != null); // [ 0, 1, '', false, NaN ]
// ⭐ 3. Remove all "holes" (and only holes)❗
arr.filter(() => true); // [ 0, 1, '', false, undefined, null, NaN ]
// ⭐ 4. Remove all "falsy values"
// --------------------------------
// falsy values: false, 0, 0n, "", null, undefined, NaN
arr.filter(Boolean); // [ 1 ]
Last updated
Was this helpful?