gpt4 book ai didi

Javascript 三元 w/for 循环错误; "Uncaught SyntaxError: Unexpected token for"

转载 作者:行者123 更新时间:2023-11-30 16:19:12 25 4
gpt4 key购买 nike

我无法弄清楚为什么我不能在三元运算中使用我的 for 循环。这是不起作用的代码:

this.ask = function() {
m = (isVoice) ? 'voice' : 'text';
switch (true) {
case m == 'voice' && typeof questions[timer.question].voice == 'string':
(++timer.attempts > timer.maxAttempts) ?
console.log('Stop'):
console.log('Play file (' + timer.attempts + '): ' + questions[timer.question].voice);
break;
case m == 'voice' && typeof questions[timer.question].voice == 'object':
(++timer.attempts > timer.maxAttempts) ?
console.log('Stop'):
for (i = 0; i < questions[timer.question].voice.length; i++) {
console.log(questions[timer.question].voice[i])
};
break;
default:
(++timer.attempts > timer.maxAttempts) ?
console.log('Stop'):
console.log('Say Text (' + timer.attempts + '): ' + questions[timer.question].text);
break;
}
};

特别是 m == 'voice' 和 typeof == 'object' 的情况会抛出错误“Uncaught SyntaxError: Unexpected token for”。如果我将那个案例更改为:

case m == 'voice' && typeof questions[timer.question].voice == 'object':
console.log('Audio, Array.');
if (++timer.attempts > timer.maxAttempts) {
console.log('Stop');
}
else {
for (i in questions[timer.question].voice) {
console.log(questions[timer.question].voice[i]);
}
}
break;

...然后一切都按预期进行。

这是为什么??

最佳答案

三元运算符的语法要求“分支”是表达式。您不能只是在那里放置任何任意语句;在 JavaScript 中,for 循环不是表达式。

您可以将循环包装在一个函数中并调用它,但只使用普通的 if 语句会简单得多。

关于Javascript 三元 w/for 循环错误; "Uncaught SyntaxError: Unexpected token for",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34999973/

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