javascriptjavajavax

ScriptEngine JavaScript Doesn't Support Contains?


I've got some code like the following.

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

But that throws the following error

javax.script.ScriptException: TypeError: [1, 2, 3].contains is not a function in <eval> at line number 1

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


Solution

  • You are looking for Array.prototype.includes.

    Your code would be:

    engine.eval("[1, 2, 3].includes(1)");