僅過濾 JavaScript 中的空值


我們要求編寫一個 JavaScript 函式,它接受一個包含一些 false 值的陣列。該函式應在原地刪除陣列中所有空值(如果存在)。

例如:如果輸入陣列為 −

const arr = [12, 5, undefined, null, 0, false, null, 67, undefined, false, null];

則輸出應為 −

const output = [12, 5, undefined, 0, false, 67, undefined, false];

示例

程式碼如下 −

const arr = [12, 5, undefined, null, 0, false, null, 67, undefined,
false, null];
const removeNullValues = arr => {
   for(let i = 0; i < arr.length; ){
      // null's datatype is object and it is a false value
      // so only falsy object that exists in JavaScript is null
      if(typeof arr[i] === 'object' && !arr[i]){
         arr.splice(i, 1);
      }else{
         i++;
         continue;
      };
   };
};
removeNullValues(arr);
console.log(arr);

輸出

控制檯中的輸出 −

[ 12, 5, undefined, 0, false, 67, undefined, false ]

更新日期: 2020-10-10

325 次瀏覽

開啟你的職業生涯

完成課程獲得認證

開始學習
廣告