ckinmind / JS-Algorithm

整理javascript的算法问题,题目来自FreeCodeCamp, CodeWars等, 请看Issues
1 stars 0 forks source link

数组过滤布尔值为false的值 #5

Open ckinmind opened 7 years ago

ckinmind commented 7 years ago

题目来自FCC: Falsy Bouncer, 过滤数组中false, null, 0, "", undefined, and NaN 这些值,题目很简单

function bouncer(arr) {r.
 return arr.filter(function(v){
   return Boolean(v);
  });
}

bouncer([false, null, 0, NaN, undefined, ""]);

Boolean()方法可以将false, null, 0, "", undefined, and NaN,返回false

ckinmind commented 7 years ago

本题很简单,但是看了大神的答案每次都有新体会

function bouncer(arr) {
  // Boolean is a function so it acts as a callback here instead of Boolean(arg)
  return arr.filter(Boolean);
}

bouncer([7, "ate", "", false, 9]);

因为Boolean就是方法,可以直接当成回调函数