admin管理员组文章数量:1420112
I'm trying to filter a list of elements by their index, and it is possible that the first item is the item I want to get.
It seems that trying to filter a 0
using
arr.filter(function(f) {
if (Number.isInteger(f)) return f;
});
does not work. Though Number.isInteger(0)
is true.
Here's a fiddle I've created to show an example. The array filtered should have two values, not one.
/
I'm trying to filter a list of elements by their index, and it is possible that the first item is the item I want to get.
It seems that trying to filter a 0
using
arr.filter(function(f) {
if (Number.isInteger(f)) return f;
});
does not work. Though Number.isInteger(0)
is true.
Here's a fiddle I've created to show an example. The array filtered should have two values, not one.
https://jsfiddle/yb0nyek8/1/
Share Improve this question edited Apr 24, 2016 at 8:28 Hamms 5,10723 silver badges29 bronze badges asked Apr 24, 2016 at 5:23 pedalpetepedalpete 21.6k45 gold badges133 silver badges245 bronze badges3 Answers
Reset to default 8because 0 is a falsey value in javascript returning f where f is 0 will essentially be returning false.
arr.filter(Number.isInteger)
should be all you need since filter wants a function that returns true or false anyways.
The statement within your .filter()
function is returning 3
, 0
, undefined
, which in the truthy/falsey universe is true
, false
, false
. This means the return from the .filter()
function is [3]
.
If you want to return all integer values use the following:
var a1 = arr.filter(function(f) {
return Number.isInteger(f);
});
This will return [3,0]
from the .filter()
function.
Array.filter runs a given function on each item in the array, and decides whether to keep it or toss it based on whether the function returns true or false. There's no need to return the number on your own.
By returning the number itself, you end up returning the number 0, which array.filter perceives as "false", causing it to not include it.
Since Number.isInteger() returns a true or false on its own, just use it by itself.
arr.filter(function (f){
Number.isInteger(f);
})
本文标签: javascriptFilter an array of numbers where 0 is a valid inputStack Overflow
版权声明:本文标题:javascript - Filter an array of numbers where 0 is a valid input - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745326598a2653619.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论