【问题标题】:Javascript ternary w/ for loop error; "Uncaught SyntaxError: Unexpected token for"带有for循环错误的Javascript三元; “未捕获的语法错误:意外的令牌”
【发布时间】:2016-01-25 18:45:18
【问题描述】:

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

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

这是为什么呢??

【问题讨论】:

  • 在三元中你需要使用返回一些值的表达式,for循环不返回任何东西。
  • 三元运算符非常方便,但它也为不可读的意大利面条代码留下了一个漏洞。在我看来,这就是其中之一。我不建议以这种方式编写代码。使用if
  • 我采用了许多人指出的...简单的 if/else 语句,代码更简洁。谢谢大家的意见。感谢 Pointy 解释问题所在。

标签: javascript for-loop ternary


【解决方案1】:

三元运算符的语法要求“分支”是表达式。你不能随便放任何陈述;在 JavaScript 中,for 循环不是表达式。

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

【讨论】:

    【解决方案2】:

    如果您将 for 循环括在括号中,它可能会起作用。

    function() {
        for (i = 0; i < questions[timer.question].voice.length; i++) {
         console.log(questions[timer.question].voice[i])
        }
    }()
    

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator

    但从风格上讲,你真的在​​挑战极限......

    【讨论】:

    • 这也是语法错误。同一个,事实上,并且出于相同的原因。一旦你以( 开始语句,唯一可以跟随的就是一个表达式,而for 不是一个可以开始部分表达式的标记。
    • 对。正如@Pointy 之前所说,实现这一目标的唯一方法是立即执行匿名函数。
    猜你喜欢
    • 1970-01-01
    • 2014-02-09
    • 2011-04-07
    • 1970-01-01
    • 1970-01-01
    • 2014-05-09
    • 2014-11-24
    • 2012-09-07
    • 2015-03-21
    相关资源
    最近更新 更多