zoukankan      html  css  js  c++  java
  • Falsy Bouncer(算法)

    题目

    真假美猴王!

    删除数组中的所有假值。

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

     
  • 相关阅读:
    转:PCIe基础知识
    转:HDMI介绍与流程
    Java EJB JBoss
    冒泡排序
    多线程
    快排
    Talk is cheap,show me the code
    oracle union
    Oracle 【to_number】【instr】
    DB 【ACID】
  • 原文地址:https://www.cnblogs.com/codepen2010/p/6824888.html
Copyright © 2011-2022 走看看