我正在尝试编写一个函数sortBool(arr),它接受一个数组,并返回一个对象,其中包含找到的每种假值的计数。
例如:
sortBool([1, 0, 10, 2-2, Math.sqrt(-1)]); // should return {0: 2, NaN: 1}到目前为止:
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; 发布于 2019-02-19 05:57:14
您可以检查该值,然后通过将该值作为键进行计数。
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)]));
发布于 2019-02-19 06:08:25
@Nina Scholz的答案是正确的,是一个很好的解决问题的方法。学习JavaScript,从长远来看,这是一条必由之路。
以防它同时需要太多新概念,我提供了一个更符合您实现的功能的解决方案:
// 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;
}正如您所看到的,该方法比使用reduce的方法略长,但在功能上是相同的。真的,这是完全一样的。
https://stackoverflow.com/questions/54755871
复制相似问题