簡體   English   中英

在 JavaScript 中從數組中過濾 null

[英]Filter null from an array in JavaScript

我的任務是從給定數組中刪除 false、null、0、""、undefined 和 NaN 元素。 我研究了一個解決方案,它刪除了除 null 之外的所有內容。 任何人都可以解釋為什么? 這是代碼:

function bouncer(arr) {
var notAllowed = ["",false,null,0,undefined,NaN];
  for (i = 0; i < arr.length; i++){
      for (j=0; j<notAllowed.length;j++) {
         arr = arr.filter(function(val) {
               return val !== notAllowed[j];
              });
  }
 }
return arr;
}

bouncer([1,"", null, NaN, 2, undefined,4,5,6]);

好吧,既然你所有的值都是假的,就做一個!! (轉換為布爾值)檢查:

[1,"", null, NaN, 2, undefined,4,5,6].filter(x => !!x); //returns [1, 2, 4, 5, 6]

編輯:顯然不需要演員表:

 document.write([1,"", null, NaN, 2, undefined,4,5,6].filter(x => x));

上面的代碼刪除了""nullundefinedNaN就好了。

這是NaN的問題,因為

NaN !== NaN

在此處閱讀更多信息: 針對NaN測試

為了過濾值,您可以檢查真實性。

 function bouncer(arr) { return arr.filter(Boolean); } console.log(bouncer([1, "", null, NaN, 2, undefined, 4, 5, 6]));

您可以使用Array.prototype.filter進行值檢查 - 請參見下面的演示:

 function bouncer(array) { return array.filter(function(e) { return e; }); } console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

 function bouncer(arr) { return arr.filter(function(item){ return !!item; }); } console.log(bouncer([1,"", null, NaN, 2, undefined,4,5,6]));

[1, 2, 0, null, "sdf", ""].filter(a=>a)
// filter non null value, remove 0, null and "" (empty quote)

 console.log([1, 2, 0, null, "sdf", ""].filter(a=>a))

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM