码迷,mamicode.com
首页 > 编程语言 > 详细

Falsy Bouncer(算法)

时间:2017-05-08 16:02:08      阅读:135      评论:0      收藏:0      [点我收藏+]

标签:oci   生成   developer   lob   body   tps   soc   word   targe   

题目

真假美猴王!

删除数组中的所有假值。

在JavaScript中,假值有false、null、0、""、undefined 和 NaN。

提示

Boolean Objects

Array.filter()

思路

我们可以用  Boolean() 函数进行类型转换。如果它的参数是 0、-0、null、undefined、false、NaN、"",生成的Boolean对象的值会为false,也就是题目中说的“假值”。 

解法

解法一

function bouncer(arr) {
  // Don‘t show a false ID to this bouncer.
  return arr.filter(function(item,index,array){
    return Boolean(item);
  });
}

解法二

function bouncer(arr) {
  // Don‘t show a false ID to this bouncer.
  return arr.filter(Boolean);
}

测试

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]. 

 

Falsy Bouncer(算法)

标签:oci   生成   developer   lob   body   tps   soc   word   targe   

原文地址:http://www.cnblogs.com/codepen2010/p/6824888.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!