【问题标题】:Unable to parse full javascript if statement from within Java using javascript无法使用 javascript 从 Java 中解析完整的 javascript if 语句
【发布时间】:2011-07-18 18:13:17
【问题描述】:

所以我发布了这个问题 Putting a simple expression language into java 并得到了关于使用 ScriptEngine 允许用户编写我所做的 javascript 并且它似乎工作的很好的答案

但是像

这样的表达式
(artist.length>0 ? artist + '-' :'') + (album.length>0 ? album + '-' :'')

使用完整的 if 语句不工作

if(artist.length>0) {artist + ':-'}   + (album.length>0 ? album + '-' :'') 

你可能会问我为什么要这样做,我希望我可以使用 if:else if:else 语句,这是朝着那个方向迈出的一步

【问题讨论】:

  • java != javascript ...
  • @Neal:OP 正在询问使用 JSR-223 从 Java 运行的 JS 代码。有时这种上下文很重要,因此 OP 提到了它。

标签: java javascript rhino scriptengine


【解决方案1】:

这根本不是有效的 javascript。

<cond> ? <iftrue> : <iffalse>

是if-else的'表达式'形式,返回可以使用的值。

if {

} else {

}

是“语句”版本,用于执行代码,不返回值。

【讨论】:

  • 感谢您在这里暴露了我对 javascript 的无知,所以我是否可以在表达式中做相当于 if else if else 的操作
  • 你可以嵌套表达式,比如 ? b : (c ? d : e),翻译为:如果 a,则 b,否则如果 c,则 d,否则 e
  • 感谢工作,即 (albumartist.length>0 ? albumartist :(artist.length>0 ? artist : ' '))
猜你喜欢
  • 2011-06-22
  • 2015-07-12
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多