forEach / for ...没有返回值? [英] forEach/for...in not returning values?

查看:295
本文介绍了forEach / for ...没有返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我有点困惑,我在 freeCodeCamp 上解决了一个挑战。

So I have a little bit of confusion, I'm solving a challenge on freeCodeCamp.

挑战读取如下


一切都是真的

检查如果谓词(第二个参数)对集合的所有元素(第一个参数)都是真实的。

Check if the predicate (second argument) is truthy on all elements of a collection (first argument).

它已经解决了但是我没有明白为什么我不得不采取额外措施。我的代码是这样的:

It's solved but I don't understand why I had to take an extra step. My code is as such:

function truthCheck(collection, pre) {
    collection.forEach(function(element) {
        for (key in element) {
            if (!element.hasOwnProperty(pre)) {
                return false;
            } else if (key === pre) {
                if (!Boolean(element[key])) {
                    return false;
                }
            }
        }
    });
    return true;
}

truthCheck([
    {"user": "Tinky-Winky", "sex": "male"},
    {"user": "Dipsy"},
    {"user": "Laa-Laa", "sex": "female"},
    {"user": "Po", "sex": "female"}
], "sex");

所以在这个例子中它应该失败,因为集合中的第二个元素没有 sex 属性。如果 pre 参数,或者在这种情况下 sex 不是真值,你也会收到失败。

so in this instance it should fail because the 2nd element within collection does not have the sex property. Also you will receive a fail if the pre argument, or in this case sex is not a truthy value.

当这些被击中时(我们可以通过控制台日志告诉它)但我认为它会突破循环并从<$ c $返回c> truthCheck function .....但它没有,它最终会返回true。

When these get hit (Which they are, I'm able to tell through console logs) but I figure it would break out of the loop and return from the truthCheck function.....but it doesn't, and it will eventually return true.

我能绕过这个通过定义一个变量,然后将该值设置为false,然后在结尾处返回该变量。有没有更好的办法?似乎这些返回应该突破 truthCheck 函数?我错过了什么吗?

I was able to circumvent this by defining a variable and then setting that value to false and then returning the variable at the end. Is there a better way? It seems like these returns should break out of the truthCheck function? Am I missing something?

推荐答案

正如其他答案所解释的那样,这是没有意义的:

As the other answers explain, this is meaningless:

collection.forEach(function () {
  // do something
  return false;
});

因为数组#forEach 根本不关心为其工作函数的返回值。它只是为每个数组元素执行worker函数。

because array#forEach simply does not care for the return value of its worker function. It just executes the worker function for each array element.

你可以使用worker函数来设置一个外部变量:

You could use the worker function to set an outer variable:

function truthCheck(collection, pre) {
  var allAreTruthy = true;
  collection.forEach(function (elem) {
    // if this ever flips allAreTruthy to false, it will stay false
    allAreTruthy = allAreTruthy && elem[pre];
  });
  return allAreTruthy;
}

但是有更好的方法来表达这一点。

But there are better ways to express this.


检查谓词(第二个参数)是否对集合的所有元素(第一个参数)都是真实的。

Check if the predicate (second argument) is truthy on all elements of a collection (first argument).

可以解释为该集合的每个元素在特定键上都具有真实价值。

Could be paraphrased as "Every element of the collection has a truthy value at a particular key."

function truthCheck(collection, pre) {
  return collection.every(function (elem) { return elem[pre]; });
}

可以解释为该集合的元素在特定键上具有虚假值(或完全没有键)。

Could be paraphrased as "None of the elements of the collection have a falsy value at a particular key (or are missing the key entirely)."

或者,因为数组#none 方法实际上并不存在,集合中没有某些元素在特定键上具有虚假值。

Or, since an Array#none method does not actually exist, "There aren't some elements of the collection that have a falsy value at a particular key."

function truthCheck(collection, pre) {
  return !collection.some(function (elem) { return !elem[pre]; });
}

使用 Array#some 是只要满足它所寻求的条件,它就会停止迭代数组。如果您的阵列有许多元素,这将意味着提高性能。对于短阵列,使用 Array#every Array#forEach

The advantage of using Array#some is that it stops iterating the array as soon as the condition it seeks for is fulfilled. If your array had many elements this would mean improved performance. For short arrays there's not a lot of difference to using Array#every or Array#forEach.

以上在语义上相当于

function truthCheck(collection, pre) {
  var i;
  for (i = 0; i < collection.length; i++) {
    if (!collection[i][pre]) return false;
  }
  return true;
}

因为JS对象只返回 undefined 当你访问一个尚未设置的密钥时,检查 hasOwnProperty 在这里是多余的。

Since JS objects simply return undefined when you access a key that has not been set, a check for hasOwnProperty is superfluous here.

这篇关于forEach / for ...没有返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆