JavaScript基础算法——过滤数组假值

126 阅读1分钟

要求:

删除数组中的所有假值。

在JavaScript中,假值有falsenull0""undefinedNaN

样本:

bouncer([7, "ate", "", false, 9])应该返回 [7, "ate", 9].

bouncer(["a", "b", "c"]) 应该返回 ["a", "b", "c"].

bouncer([false, null, 0, NaN, undefined, ""]) 应该返回 [].

bouncer([1, null, NaN, 2, undefined]) 应该返回 [1, 2].

解法:

function bouncer(arr) {
  return arr.filter(a => a);
}

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