三元运算符始终评估真实部分
我有一个声明:
var sep = ' | ';
var r = '';
for (var i = 0; i < menuItems.length; i++) {
r += function(menuObject) {
console.log(menuObject);
console.log(
'<a class="" href="' +
menuObject.url + '">' + menuObject.name + '</a>' +
(i < menuItems.length - 1) ? sep : ""); //logs the contents of sep
) //console.log expanded for readability
}
}
为什么它不记录完整的字符串,而只评估 sep
?
I have a statement:
var sep = ' | ';
var r = '';
for (var i = 0; i < menuItems.length; i++) {
r += function(menuObject) {
console.log(menuObject);
console.log(
'<a class="" href="' +
menuObject.url + '">' + menuObject.name + '</a>' +
(i < menuItems.length - 1) ? sep : ""); //logs the contents of sep
) //console.log expanded for readability
}
}
Why is it not logging the full string, and instead only evaluating to sep
?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
因为您没有将 if 行括在括号中,并且它会将其之前的所有字符串作为条件进行处理。
试试这个...
Because you are not wrapping your if line in parenthesis and it is process all of the string before it as the condition.
Try this...
问题在于运算符优先级。
正在执行(注意我添加的额外括号)。当使用三元运算符时(顺便说一句,它与 if 子句关系不大),您应该始终使用括号,如下所示:
The issue is operator precedence.
is being executed (mind the extra parenthesis I added). When using the ternary operator (which has only little to do with
if
clauses btw.) you should always use parenthesis like here:运算符优先级。将表达式放在
?
之前的括号中:Operator precedence. Put your expression before
?
in parentheses: