简体   繁体   English

为什么此代码不适用于字符串?

[英]Why won't this code work on a string?

So i am practicing algorithms(javascript), and i come across this challenge, where we have to filter an array, remove the following elements:所以我正在练习算法(javascript),我遇到了这个挑战,我们必须过滤一个数组,删除以下元素:

false, NaN, undefined, "", null, 0假,NaN,未定义,“”,空,0

My code seems to have problems with strings and chars, it failed these tests.我的代码似乎在字符串和字符方面有问题,它没有通过这些测试。

-bouncer([7, "ate", "", false, 9]) should return [7, "ate", 9] (returned [7, 9]) -bouncer([7, "ate", "", false, 9]) 应该返回 [7, "ate", 9] (返回 [7, 9])

-bouncer(["a", "b", "c"]) should return ["a", "b", "c"] (returned []) -bouncer(["a", "b", "c"]) 应该返回 ["a", "b", "c"] (返回 [])

    function bouncer(arr) {
        return arr.filter(function(element)
                {
                    if (element != false && !isNaN(element) && element != null && element != "" && element != undefined)
                        {return element;}
                }
               );
    }

I would love a simple explanation of the concept i am missing我想对我缺少的概念做一个简单的解释

function bouncer(arr) {
    return arr.filter(function(element) {
            if (element) {
                return element;
            }
        }
    );
}

Here is the answer for you.这是给你的答案。

Beside the given coercion propblem with != instead of !== , you could filter by using Boolean as callback, which returns truthy elements.除了使用!=而不是!==给定的强制转换问题之外,您还可以使用Boolean作为回调进行过滤,该回调返回真实元素。

 function bouncer(arr) { return arr.filter(Boolean); } console.log(bouncer([7, "ate", "", false, 9])); // [7, "ate", 9] console.log(bouncer(["a", "b", "c"])); // ["a", "b", "c"]

The below code works for all the conditions.以下代码适用于所有条件。 Please have a look at it.请看一看。

function bouncer(arr) {
    return arr.filter(function(element) {
        if (element && element.trim().length > 0 && element != "NaN") {
            return element;
        }
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM