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

标签 javascript for-loop ternary

我无法弄清楚为什么我不能在三元运算中使用我的 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/

相关文章:

C++ : Ternary Operator (Conditional Operator) and its Implicit Type Conversion Rules

javascript - 将字符串从 JSON.stringify 转换回数组

javascript - 未捕获的类型错误 : Cannot read property 'toArrays' of undefined

javascript - 单击“来自 Json 的复选框”时不显示警报

java - 在循环体中创建新对象

php - 改进 PHP 'for' 循环

c - C 中没有 else 的三元运算符

javascript - 是否有与 <noscript> 相反的 HTML?

PHP for 循环与 C for 循环

algorithm - 将流式数据转换为三元(base-3)