Javascript 如何过滤()出数组中的 NaN、null、0、false(JS)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/31925323/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to filter() out NaN, null, 0, false in an array (JS)
提问by Fhrey
I was asked to filter out NaN, null, 0, falsein an array.
有人问我,以过滤掉的NaN,NULL,0,假以阵列。
Luckily I have answered the question.
幸运的是我已经回答了这个问题。
function bouncer(arr) {
function filterer(arr) {
return arr > 0|| isNaN(arr) === true;
}
arr = arr.filter(filterer);
return arr;
}
//example input
bouncer([0, 1, 2, 3, 'ate', '', false]); //output [1, 2, 3, 'ate']
but the thing is I really don't know how I came up with the answer or rather I don't know how it works. Specially on arr > 0how did the filter know that arr is alread on arr[1], arr[2], etc.. without using a loop to iterate in all array.
但问题是我真的不知道我是如何想出答案的,或者更确切地说,我不知道它是如何工作的。特别是在arr > 0上,过滤器如何知道 arr 已经在 arr[1]、arr[2] 等上......而不使用循环来迭代所有数组。
or can simply just explain on how to code works. [I've tried to explain it clearly ---]
或者可以简单地解释如何编码工作。[我试图解释清楚---]
采纳答案by Matt Burland
Look at the docsfor Array.filter
. Notice in particular the arguments to the callback:
看文档的Array.filter
。特别注意回调的参数:
Function to test each element of the array. Invoked with arguments (element, index, array). Return true to keep the element, false otherwise.
用于测试数组每个元素的函数。使用参数(元素、索引、数组)调用。返回 true 以保留元素,否则返回 false。
So in your case arr
is the element (and poorly named, hence your confusion). Filter loops through your array and for every item it calls you callback passing in the element at the current position as arr
.
因此,在您的情况下arr
是元素(并且名称很差,因此您很困惑)。过滤器循环遍历您的数组,对于它调用的每个项目,将当前位置的元素作为arr
.
As others have pointed out in the comments, the logic of your filter callback is actually flawed for negative values, but that may not be an issue if you know that your array will never contain negative values (but that can be a dangerous thing to assume).
正如其他人在评论中指出的那样,您的过滤器回调的逻辑实际上对于负值存在缺陷,但是如果您知道您的数组永远不会包含负值(但这可能是一件危险的事情),这可能不是问题)。
And, of course, internally, this is looping through your array. You can't filter your (unsorted) array without touching each element in the array. Look at the polyfil in the link to get an idea of how it mightwork (might because this is an implementation detail that may differ with different javascript engines, but will no doubt involve a loop somewhere), it loops through your array, calls the callback (note the arguments) and if the callback returns true, it gets pushed onto a results array.
而且,当然,在内部,这是循环遍历您的数组。您无法在不触及数组中的每个元素的情况下过滤(未排序的)数组。看在链接的polyfil得到它是如何的想法可能工作(威力,因为这是一个实现细节可以与不同的JavaScript引擎不同,但无疑会涉及到循环的地方),它遍历您的数组,调用回调(注意参数),如果回调返回 true,则将其推送到结果数组中。
回答by Bluefin
If you were asked to filter out NaN
, null
, 0
, false
in an array, then your solutions doesn't really work.
如果你被要求过滤掉NaN
,null
,0
,false
在一个数组,那么您的解决方案并没有真正发挥作用。
Your input of:
您的输入:
bouncer([0, 1, 2, 3, 'ate', '', false, NaN]);
Will get the output of:
将得到以下输出:
[1, 2, 3, 'ate', NaN]
To filter out all 'falsy' values you can simply use Boolean
:
要过滤掉所有 'falsy' 值,您可以简单地使用Boolean
:
function bouncer(arr) {
return arr.filter(Boolean);
}
bouncer([0, 1, 2, 3, 'ate', '', false, NaN]);
Output:
输出:
[1, 2, 3, 'ate']
Since the Boolean
constructor is also a function, it returns either true
for ‘truthy' argument or false
for ‘falsy' argument. If the value is omitted or is 0
, -0
, null
, false
, NaN
, undefined
, or the empty string (""
), the object has the value of false. All other values, including any object or the string "false"
, create an object with an initial value of true
.
由于Boolean
构造函数也是一个函数,它返回true
“truthy”参数或false
“falsy”参数。如果该值被省略或者是0
, -0
, null
, false
, NaN
, undefined
, 或空字符串 ( ""
),则对象的值为 false。所有其他值,包括任何对象或字符串"false"
,都会创建一个初始值为 的对象true
。
回答by Trevor Dixon
You can also use an identity function instead of Boolean
.
您还可以使用标识函数而不是Boolean
.
function bouncer(arr) {
return arr.filter(x => x);
}
回答by elimcjah
I am also working on the Free Code Camp Falsy Bouncer Algorithm. I have found the simplest way to do it is:
我也在研究 Free Code Camp Falsy Bouncer 算法。我发现最简单的方法是:
function bouncer(arr) {
return arr.filter(Boolean);
}
回答by Ravi Kumar Seth
The filter()method creates a new array with all elements that pass the test implemented by the provided function.
所述过滤器()方法创建与通过由提供的功能实现的测试中所有元素的数组。
Since false
, null
, 0
, ""
, undefined
and NaN
are all Falsyvalues in JavaScript therefore they will return falsewhen tested.
因为false
,null
,0
,""
,undefined
和NaN
都Falsy在JavaScript中的值,因此他们将返回错误的测试时。
function bouncer(arr) {
var array = arr.filter(function(val){
return val;
});
return array;
}
Only values which do not return falsewill be added to the array.
只有不返回 false 的值才会被添加到数组中。
回答by adam bahdaj
Wouldn't be more elegant to base on assumption that all unwanted elements are casted to false when boolean expected, so:
假设所有不需要的元素在布尔值预期时都被转换为 false 不会更优雅,所以:
function clear (arr){
var stripped = [];
for (i = 0, len = arr.length; i < len; i++){
if (arr[i])
stripped.push(arr[i]);
}
return stripped;
}
回答by Manwal
Function to test each element of the array. Invoked with arguments (element, index, array). Return true to keep the element, false otherwise
用于测试数组每个元素的函数。使用参数(元素、索引、数组)调用。返回 true 以保留元素,否则返回 false
If you just want explanation. Array filter()
as name suggest. Remove unwanted element if condition falls wrong (false).
如果你只是想解释。filter()
顾名思义的数组。如果条件出错(false),则删除不需要的元素。
(arr > 0|| isNaN(arr) === true
)
( arr > 0|| isNaN(arr) === true
)
0, false || false //removed
1, true || false
2, true || false
3, true || false
'ate', false || true
'', false|| false // removed
false false || false //removed
Output:
输出:
[1, 2, 3, "ate"]
回答by Jose manuel Alves Sousa
Since i′m a beginner o coding, my logic went to use primitive Boolean′s to compare the item′s filtered, but this was before I have read the Boolean Object reference, you see is that like its written there, "The value passed as the first parameter is converted to a Boolean value if necessary. If value is omitted or is 0, -0, null, false, NaN, undefined, or the empty string (""), the object has an initial value of false. All other values, including any object or the string "false", create an object with an initial value of true." So the logic since filter returns the value if it′s true or false, you should return values if they are true. Also, I didn′t learn everything about the filter method, for what I have researched, I have got a bit more of information, that I will try to explain here.′
由于我是初学者 o 编码,我的逻辑去使用原始布尔值来比较项目的过滤,但这是在我阅读布尔对象引用之前,你看到就像它写的那样,“传递的值作为第一个参数在必要时转换为布尔值。如果 value 被省略或为 0、-0、null、false、NaN、undefined 或空字符串 (""),则对象的初始值为 false。所有其他值,包括任何对象或字符串“false”,都会创建一个初始值为 true 的对象。因此,如果过滤器为真或假,则逻辑返回值,如果它们为真,您应该返回值。另外,我并没有完全了解过滤方法,对于我所研究的,我得到了更多的信息,我将在这里尝试解释。'
redefining the method (it already exists, is just for understanding) the filter method accepts a function called a predicate, that is a function that receives a value and returns true or false.
重新定义方法(它已经存在,只是为了理解)过滤器方法接受一个称为谓词的函数,它是一个接收值并返回真或假的函数。
The var results is an empty array where the results will be pushed with the push method. The we use a forEach method with this, (this, in this context is applied to the array prototype ,this means that you will have the filter method available on every array that you define, with the sintax of array.method(args) ins this case array.filter(args)) some resources https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
var results 是一个空数组,其中的结果将使用 push 方法推送。我们使用了一个 forEach 方法,(这个,在这个上下文中应用于数组原型,这意味着你将在你定义的每个数组上都有可用的过滤器方法,数组的语法是 array.method(args) ins这种情况下 array.filter(args)) 一些资源 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/prototype
Now we will run an operation in every item on the the array, with the forEach method, now we will apply the predicate function to itch item of the array and if it returns true, will add it to the results.
现在我们将对数组上的每个项目运行一个操作,使用 forEach 方法,现在我们将谓词函数应用于数组的 itch 项目,如果返回 true,则将其添加到结果中。
Array.prototype.filter = function(predicate){
var results = [];
this.forEach(function(item) {
if (predicate(item)) {
results.push(item);
}
});
};
//-------------------------------Correct Solution---------------------------
//-------------------------------正确的解决方法-------------- ------------
function bouncer (arrToFilter){
return arrToFilter.filter(Boolean);
}
//----------Code without the filter method---------
//-----------没有过滤器方法的代码---------
function bouncerNoFilterMethod(arrToFilter){
var results = [];
arrToFilter.forEach(function(arrToFilter){
if(arrToFilter){
results.push(arrToFilter);
}
});
return results;
}
console.log(bouncerNoFilterMethod([7, "ate", "", false, 9]));
console.log(bouncerNoFilterMethod(["a", "b", "c"]));
console.log(bouncerNoFilterMethod([false, null, 0, NaN, undefined, ""]));
console.log(bouncerNoFilterMethod([1, null, NaN, 2, undefined]));
console.log(bouncer([7, "ate", "", false, 9]));
console.log(bouncer(["a", "b", "c"]));
console.log(bouncer([false, null, 0, NaN, undefined, ""]));
console.log(bouncer([1, null, NaN, 2, undefined]));
Hope this helps to understand, the method, and the first thing that was not understanding was the part of passing the function, the predicate to the method, if I have mistakes here please suggest corrections.
希望这有助于理解方法,首先不理解的是传递函数的部分,方法的谓词,如果我在这里有错误请提出更正。
回答by Holden
Looks like Boolean is the simplest fix/answer for the "FreeCodeCamp" challenge, however it might be useful to try a couple of things just to get the hang of "why" and "how".
看起来 Boolean 是“FreeCodeCamp”挑战的最简单的修复/答案,但是尝试一些事情来了解“为什么”和“如何”可能会很有用。
function bouncer(arr) {
return arr.filter(function(val){
return val;
});
}
This evaluates everything passing through the filter, using the function(callback) passed in, which returns values. If it doesn't return a value, which null etc won't, it won't be included in the return. At least this method helped me understand why rather than just pass the test.
这使用传入的函数(回调)评估通过过滤器的所有内容,该函数返回值。如果它不返回一个值,而 null 等则不会,它不会被包含在返回值中。至少这种方法帮助我理解为什么而不是仅仅通过测试。
回答by Greald Henstra
I slightly modified https://stackoverflow.com/a/35327425/3932895to set everything to zero that has no numerical value
我稍微修改了https://stackoverflow.com/a/35327425/3932895将没有数值的所有内容都设置为零
function zerofy(x){return (Boolean(x) && !isNaN(x.toString())) ? x : 0 ;}
Tested with
测试过
function clear (arr){
var stripped = [];
for (i = 0; i < arr.length; i++){
stripped.push(zerofy(arr[i]));
}
return stripped;
}
in
在
clear(["written",13,0,-4,5,true,false,undefined,null,NaN,Math.PI]);
results to
结果
[0,13,0,-4,5,0,0,0,0,0,3.141592653589793]
[0,13,0,-4,5,0,0,0,0,0,3.141592653589793]