javascriptjavanashornjavax

ScriptEngine JavaScript Doesn't Support Includes?


I've got some code like the following.

ScriptEngineManager manager = new ScriptEngineManager();
ScriptEngine engine = manager.getEngineByName("nashorn");
engine.eval("[1, 2, 3].includes(1)");

But that throws the following error

javax.script.ScriptException: TypeError: [1, 2, 3].includes is not a function in <eval> at line number 1
    at jdk.nashorn.api.scripting.NashornScriptEngine.throwAsScriptException(NashornScriptEngine.java:470)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:454)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:406)
    at jdk.nashorn.api.scripting.NashornScriptEngine.evalImpl(NashornScriptEngine.java:402)
    at jdk.nashorn.api.scripting.NashornScriptEngine.eval(NashornScriptEngine.java:155)
    at javax.script.AbstractScriptEngine.eval(AbstractScriptEngine.java:264)

I can do indexOf(1) instead and that seems to work, but is there a reason why I don't have access to includes with this parser?


Solution

  • String.prototype.includes is specified in ECMAScript 2015 ( ECMA-262 6th Edition). Nashorn engine implements ECMA-262 Edition 5.1). See also http://www.ecma-international.org/ecma-262/6.0/#sec-string.prototype.includes

    https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes has a polyfill for String.prototype.includes. I checked that the polyfill works with Nashorn engine.