Javascript 三元,带循环错误;“未捕获的语法错误:意外的令牌”
Javascript ternary w/ for loop error; "Uncaught SyntaxError: Unexpected token for"
我无法弄清楚为什么我不能在三元运算中使用我的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' 抛出错误"未捕获的语法错误:意外令牌"的情况。如果我将这种情况更改为:
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
语句会简单得多。
如果你把你的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
但从风格上讲,你真的是在挑战极限......
相关文章:
- 错误:语法错误,无法识别的表达式:不支持的伪:无效/RectJS/Unit Testing
- 未捕获错误:语法错误,无法识别的表达式:input[@type=submit]
- jQuery AJAX Post方法错误(语法错误)
- 如何“;修复解析错误:语法错误,意外'{'in”用于php
- 错误:错误:语法错误,无法识别的表达式:
- 未捕获错误:语法错误,无法识别的表达式:ajaxsample/update_agenda(CodeIgniter)
- 未捕获错误:语法错误,无法识别表达式Jquery选择器单引号与双引号
- Javascript ( jQuery ) 错误: 语法错误: 缺少 ) 在参数列表之后
- 错误:语法错误:令牌“”,“”是意外的标记
- 未捕获的错误:语法错误,无法识别的表达式:输入:复选框[名称=ninja_forms_field_57[术语]]
- 未捕获的错误:语法错误,无法识别的表达式:“.b-brand-box”
- 未捕获的错误:语法错误,无法识别的表达式:href
- ReactJS 返回解析器错误语法错误:在 AJAX 调用 JAVA servlet 后出现意外的标记 a
- jQuery:未捕获错误:语法错误,无法识别的表达式
- j查询错误 - 语法错误:缺少:在属性 ID 之后
- 在使用 Gulp 在 javascript 中声明对象时,在 Git bash 中出现以下错误“语法错误:意外标识符”
- 获取未捕获错误:语法错误、无法识别的表达式
- 获取错误语法错误:属性列表 url 后缺少 }:http://localhost/mcportal/public/pos
- 为什么我收到错误“语法错误:非法字符”
- 未捕获错误:语法错误,无法识别的表达式