JavaScript數據去掉空值


js數組中過濾掉false, null, 0, "", undefined, and NaN值的方法

對於 false,null,0,undefiend,NaN直接取!得到的都是true,因此這里只需要在判斷空字符串""; 
直接看代碼:


function bouncer(arr) { // Don't show a false ID to this bouncer. return arr.filter(function(val){ return !(!val || val === ""); }); } bouncer([7, "ate", "", false, 9]);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9

運行結果:

bouncer([7, “ate”, “”, false, 9]);

當入參是[false, null, 0, NaN, undefined, ""] 
運行結果是

[]

這里要注意:NaN與任何值比較包括它自身結果都是false,因此可以使用isNaN()函數來檢查;

 

 

Array.prototype.notempty = function(){

     return  this .filter(t => t!=undefined && t!== null );
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM