[英]Why won't this code work on a string?
所以我正在练习算法(javascript),我遇到了这个挑战,我们必须过滤一个数组,删除以下元素:
假,NaN,未定义,“”,空,0
我的代码似乎在字符串和字符方面有问题,它没有通过这些测试。
-bouncer([7, "ate", "", false, 9]) 应该返回 [7, "ate", 9] (返回 [7, 9])
-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;}
}
);
}
我想对我缺少的概念做一个简单的解释
function bouncer(arr) {
return arr.filter(function(element) {
if (element) {
return element;
}
}
);
}
这是给你的答案。
除了使用!=
而不是!==
给定的强制转换问题之外,您还可以使用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"]
以下代码适用于所有条件。 请看一看。
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.