[英]Extracting falsy values from array in Javascript
I am trying to write a function sortBool(arr)
to take an array and return an object with the count for each kind of falsy value found. 我正在尝试编写一个函数
sortBool(arr)
来获取一个数组,并返回一个对象,该对象具有每种发现的虚假值的计数。
For example: 例如:
sortBool([1, 0, 10, 2-2, Math.sqrt(-1)]); // should return {0: 2, NaN: 1}
Thus far: 迄今:
const sortBool = arr => {
index = 0;
let falsyTypes = {};
while (index < arr.length) {
if(eval(arr[index])) {
index++;
}else {
//some code to determine what type of falsy value each element is and then add it to the object
}
}
return falsyTypes;
You could check the value and then count by taking the value as key. 您可以检查该值,然后通过将该值作为键来计数。
function sortBool(array) { return array.reduce((r, v) => { if (!v) { r[v] = (r[v] || 0) + 1; } return r; }, {}); } console.log(sortBool([1, 0, 10, 2 - 2, Math.sqrt(-1)]));
The answer by @Nina Scholz is correct, and is a good way of solving the problem functionally. @Nina Scholz的回答是正确的,并且是从功能上解决问题的一种好方法。 Learning JavaScript, on the long run, that is the way to go.
从长远来看,学习JavaScript是必经之路。
Just in case it requires too many new concepts at once, I'm providing a solution more in line with the function you implemented: 万一它一次需要太多新概念,我将提供一个更符合您实现的功能的解决方案:
// you don't need lambda expressions, just a plain old function
function sortBool(arr) {
var falsyTypes = {};
// you can use a for for a slightly more compact syntax
for(var index = 0; index < arr.length; index++) {
var val = arr[index];
// you don't need to eval. So please don't
if (!val) {
falsyTypes[val] = (falsyTypes[val] || 0) + 1;
}
}
return falsyTypes;
}
As you can see, the method is slightly longer than the one using reduce, but is functionally equivalent. 如您所见,该方法比使用reduce的方法略长,但在功能上是等效的。 Really, it is exactly the same.
真的,是完全一样的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.