简体   繁体   English

从数组中删除虚假值

[英]Remove Falsy Values from Array

So I am doing the FreeCodeCamp challenge "Remove all falsy values from an array." 因此,我正在执行FreeCodeCamp挑战“从数组中删除所有虚假值”。

I made a function, but for some reason it does not filter all the falsy values: 我做了一个函数,但是由于某种原因,它不能过滤所有伪造的值:

function bouncer(arr) {

function truthy(value) {
 return value !==  '' ||false || null || undefined || NaN ;
}

 var filtered = arr.filter(truthy);
 return filtered;
}

bouncer([7, "ate", "", false, 9]);

This should return 这应该返回

[7, "ate", 9], 

but instead returns 但返回

[ 7, 'ate', false, 9 ]

If I switch the order of the function truthy, the returned values changes. 如果我切换函数true的顺序,则返回的值会更改。 For example moving the '', 例如,移动“

function truthy(value) {
   return value !==  '' ||false || null || undefined || NaN ;

-----> ----->

  return false || null || undefined || NaN || " ; 

The new 新的

false || 假|| null || 空|| undefined || 未定义|| NaN || NaN || " ; returns “;返回

[ 7, 'ate', '', 9 ]

Any idea what is going on??? 知道发生了什么吗? Thanks! 谢谢!

return value !== '' ||false || null || undefined || NaN ;

This does not do what you think it does. 这并没有按照您的想法做。 It's actually equivalent to 实际上等于

(((((value !== '') || false) || null) || undefined) || NaN)

When value !== '' , as in most of your cases, this expression is true. 在大多数情况下,当value !== '' ,此表达式为true。 You would actually need to check 您实际上需要检查

value !==  '' && value !== false && value !== null && value !== undefined && value !== NaN

But since these are all falsy anyway and Array.filter only cares about truthiness and falsiness, you can replace your truthy function with 但是由于这些都是虚假的,并且Array.filter只在乎真实性和虚假性,因此您可以用替换truthy函数

function truthy(value) {
  return value;
}

which isn't even worth breaking out three lines for: 甚至不值得为以下三行打断:

var filtered = arr.filter(e => e);

In addition to AuxTaco's answer ... 除了AuxTaco的答案 ...

  1. "All falsy values" include 0 as well. “所有虚假值”也包括0。

  2. You can shorten the filter expression a bit further, by using Boolean as function: 通过使用Boolean作为函数,可以进一步缩短过滤器表达式:

 function bouncer(arr) { return arr.filter(Boolean); } console.log(bouncer([7, "ate", "", false, 9, 0, NaN, null, undefined])); 

The problem is, your return statement, will always return true when the value is different than blank 问题是,当值不同于空白时,您的return语句将始终返回true。

function truthy(value) {
    return value !==  '' ||false || null || undefined || NaN ;
}

should be something like this 应该是这样的

function truthy(value) {
    falseValues = ['',false,null,undefined,NaN];
    return !falseValues.contains(value);
}

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

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