我正在尝试使用Java的脚本引擎管理器运行lodash命令。我已将lodash-4.15.0.jar文件添加到我的类路径中。
这是我的代码:
ScriptEngineManager factory = new ScriptEngineManager();
ScriptEngine engine = factory.getEngineByName("nashorn");
engine.eval("_.camelCase('TestTh@t Column'))");
我的预期结果是:testthtColumn然而我看到以下错误:
Exception in thread "main" javax.script.ScriptException: ReferenceError: "_" is not defined in <eval> at line number 1
at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:467)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:451)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:403)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:399)
at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)
at Tester.main(Tester.java:16)
Caused by: <eval>:1 ReferenceError: "_" is not defined
at jdk.nashorn.internal.runtime.ECMAErrors.error(ECMAErrors.java:57)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:319)
at jdk.nashorn.internal.runtime.ECMAErrors.referenceError(ECMAErrors.java:291)
at jdk.nashorn.internal.objects.Global.__noSuchProperty__(Global.java:1426)
at jdk.nashorn.internal.scripts.Script$\^eval\_.:program(<eval>:1)
at jdk.nashorn.internal.runtime.ScriptFunctionData.invoke(ScriptFunctionData.java:637)
at jdk.nashorn.internal.runtime.ScriptFunction.invoke(ScriptFunction.java:494)
at jdk.nashorn.internal.runtime.ScriptRuntime.apply(ScriptRuntime.java:393)
at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:446)
... 5 more
由于我一般缺乏javascript的经验,我不知道如何解决这个问题。任何帮助是极大的赞赏。谢谢!
答案 0 :(得分:0)
我最终在Java中执行此操作,而不是让lodash工作。虽然不是直接的答案,但它会返回与lodash的camelCase方法相同的答案。
public String camelCaseHeaderName(String s) {
String result = "";
boolean firstElem = false;
String[] words = s.split(" ");
for(int i = 0; i < words.length; i++) {
String[] finalWords = words[i].split("[^0-9a-zA-Z]+");
for(int j = 0; j < finalWords.length; j++) {
String tmp = finalWords[j].replaceAll("[^0-9a-zA-Z]+", "");
if(!firstElem) {
tmp = tmp.toLowerCase();
firstElem = true;
} else {
tmp = WordUtils.capitalizeFully(tmp);
}
result = result.concat(tmp);
}
}
return result;
}