gpt4 book ai didi

javascript - "else if"更大的 if/else if/else 语句中的 for 循环语句

转载 作者:行者123 更新时间:2023-11-29 22:35:45 29 4
gpt4 key购买 nike

有没有可能在 JavaScript 中做这样的事情?

if (name == 'foo') {
exampleFunction('some_arg');
}
else if (name == 'bar') {
exampleFunction('another_arg');
}
for (i in exampleObject) {
else if (name == exampleObject[i].name) {
exampleFunction(exampleObject[i].arg);
}
}
else {
exampleFunction('default')
}

我试过了,但在第 8 行得到了一个“意外的关键字 else”(for 循环中的“else if”)。还有另一种方法吗?

编辑:更新此以在循环中使用 exampleObject[i]。我的错!

最佳答案

没有。我认为实现此目的的最佳方法是将 for 循环移动到 else block 中并执行以下操作

if (name == 'foo') {
exampleFunction('some_arg');
}
else if (name == 'bar') {
exampleFunction('another_arg');
}
else {
var isFound = false;
for (i in exampleObject) {
if (name == exampleObject.name) {
exampleFunction(exampleObject.arg);
isFound = true;
}
}
if (!isFound) {
exampleFunction('default')
}
}

注意:看起来这段代码中还有其他错误。 for 循环声明了 i 迭代变量,但实际上从未使用过它。您的意思是在 for 循环中检查 if 以使用 i 而不是 name 吗?

关于javascript - "else if"更大的 if/else if/else 语句中的 for 循环语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5185311/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com