如何解决JavaScript 中 forEach() 循环内 Return 语句的意外行为
我的问题与我编写的 JavaScript 函数有关,该函数似乎表现得很奇怪。总之,即使遇到 return
语句后,函数执行似乎仍在继续 - 就好像 return
循环中的 forEach
语句被忽略一样。这很难理解,而且在我以前见过的任何语言中都不是这样。
在下面提供一个代码片段 - 我试图使代码、日志记录和注释尽可能集中和描述性,以便读者可以轻松识别问题。但是,如果您不想直接跳到代码,我也会分享问题的详细描述。
在我分享的代码中,函数 substituteWithMainColor()
将名为 color
的字符串值作为参数。它将它与对象文字数组(称为 substitutionArray
)的每个元素进行匹配,其中每个这样的对象都包含一个名为 mainColor
的成员字符串和名为 variations
的成员数组。如果函数在任何 color
数组中找到 variations
参数,则它返回找到匹配项的对象的相应 mainColor
。如果在任何对象中都找不到匹配项,则该函数返回作为参数传递的原始值。
在我的示例中,参数 "Cyan" 被传递给函数 substituteWithMainColor()
。由于数组 substitutionArray
包含 "Cyan" 作为其第三项的 variations
数组中的字符串之一,因此找到了匹配项(并且日志显示了它)。但是,此时,该函数并没有像预期的那样返回匹配的 mainColor
值 "Blue",而是忽略 return
循环内的 forEach()
语句并继续执行 forEach
循环的进一步迭代(日志也显示了这一点)。最终它执行 return
循环之后的最后一个 forEach()
语句,并返回原始的 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,sans-serif;
font-size: 12px;
}
解决方法
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
。如果有可能找不到,请添加空检查
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。