【发布时间】: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