【问题标题】:Unexpected Behavior of Return Statement inside forEach() Loop in JavaScriptJavaScript 中 forEach() 循环中返回语句的意外行为
【发布时间】:2021-08-12 14:51:28
【问题描述】:

我的问题与我编写的 JavaScript 函数有关,该函数的行为似乎很奇怪。总之,即使在遇到return 语句后,函数似乎仍在继续执行——就好像forEach 循环中的return 语句被忽略了一样。这很难理解,而且在我以前见过的任何语言中都不是这样。

在下面呈现代码 sn-p - 我已尝试使代码、日志记录和 cmets 尽可能集中且具有描述性,以便读者可以轻松识别问题。但是,如果您不想直接跳转到代码,我也会分享问题的详细描述。

在我分享的代码中,函数substituteWithMainColor() 将一个名为color 的字符串值作为参数。它将它与对象字面量的数组(称为substitutionArray)的每个元素进行匹配,其中每个这样的对象都包含一个名为mainColor 的成员字符串和一个名为variations 的成员数组。如果函数在任何variations 数组中找到color 参数,则它返回找到匹配项的对象的对应mainColor。如果在任何对象中都找不到匹配项,则该函数返回作为参数传递的原始值。

在我的示例中,参数 "Cyan" 被传递给函数 substituteWithMainColor()。由于数组 substitutionArray 包含 "Cyan" 作为其第三项的 variations 数组中的字符串之一,因此找到了匹配项(并且日志显示了它)。但是,此时,该函数并没有按预期返回匹配的 mainColor 值 "Blue",而是忽略 forEach() 循环内的 return 语句并继续执行进一步的迭代forEach 循环(日志也显示了这一点)。最终它执行forEach()循环之后的最终return语句,并返回错误的原始color值。

有人可以帮我了解可能发生的情况吗?

 const substitutionArray = [
            { mainColor: "Red", variations: ["Magenta", "Orange", "Crimson", "Coral", "Maroon"] },
            { mainColor: "Blue", variations: ["Purple", "Violet", "Cyan"] },
            { mainColor: "Green", variations: ["Teal", "Lime", "Aquamarine", "Olive"] }
        ]

        function substituteWithMainColor(color) {
            logToPage(`In substituteWithMainColor() function. Input: ${color}`);
            substitutionArray.forEach(item => {
                logToPage(`Testing input ${color} against variations of ${item.mainColor}`)
                if (item.variations.includes(color)) {
                    logToPage(`FOUND MATCH for ${color} - Main color: ${item.mainColor}. Returning ${item.mainColor}`);
                    return item.mainColor;  //Function should return from here if match is found.
                }
            });
            logToPage(`No matches found for ${color}. Returning ${color}`)
            return color;    //No matches found
        }

        function writeToPage(text) { document.body.innerHTML += `<div class = "content"> ${text} </div>`; }
        function logToPage(text) { document.body.innerHTML += `<div class = "log"> ${text} </div >`; }

        const colorName = "Cyan";
        writeToPage(`Original Color: ${colorName}`)
        writeToPage(`Returned Value: ${substituteWithMainColor(colorName)}`);   // "Blue should be returned"
        .content {
            outline: 1px solid rgb(161, 189, 135);
            padding: 5px;
            margin: 5px;
            color: rgb(255, 127, 80);
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            font-size: 16px;
            font-weight: bold;
        }

        .log {
            outline: 1px solid #ccc;
            padding: 5px;
            margin: 5px;
            color: rgb(85, 91, 122);
            font-family: Verdana, Geneva, Tahoma, sans-serif;
            font-size: 12px;
        }

【问题讨论】:

  • forEach的回调函数中的return语句仅从该回调返回,该值被忽略,不在任何地方使用。
  • 这么简单的解释——我怎么可能没有意识到它是从回调中返回的?感谢您的回复 - 您愿意将其作为正式答案以便我接受吗?

标签: javascript arrays foreach return javascript-objects


【解决方案1】:

forEach 与普通的for 循环不同。您实际上是在传递一个要在每个循环中执行的函数,因此您的 return 作用于 该函数的范围,而不是循环。

有点像这样:

for(let i = 0; i < 5; i++) {
    foo();
}

function foo() {
    // do something
    return true;
}

你可能正在寻找类似find() (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find)的东西

substitutionArray.find(item => item.variations.includes(color)).mainColor;

注意find 的返回是item 在substitutionArray 中,所以你必须在之后提取mainColor。如果您有可能找不到它,请添加一个空检查

【讨论】:

  • 感谢您的详细解答。除了了解我的代码中的错误之外,我还能够了解并应用 find() 方法。赞赏。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-15
  • 2013-01-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多