📘arr.filter()

JSobjectbuilt-inarraymethod ⟩ .filter()

⭐️ 注意:array.filter()自動略過陣列中的「洞」❗️

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