如何从Nashorn JavaScript中删除Java Map中的元素

时间:2017-09-26 10:59:47

标签: javascript java java-8 nashorn

我有一个Java HashMap,我已将其传递给脚本引擎。我想在处理条目时将其删除,因为我稍后会报告无效密钥。删除条目(delete testMap['key'];)的明显常用方法无效。

如何让这个测试通过?

@Test
public void mapDelete() throws ScriptException{
    Map<String,String> map = new HashMap<>(1);
    map.put("key","value");

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE).put ("testMap", map);
    engine.eval("delete testMap['key'];");
    Assert.assertEquals (0, map.size());
}

1 个答案:

答案 0 :(得分:3)

如果您知道自己有HashMap,则可以在Nashorn内使用Map API,即:

@Test
public void mapDelete() throws ScriptException {
    Map<String,String> map = new HashMap<>(1);
    map.put("key","value");

    ScriptEngine engine = new ScriptEngineManager().getEngineByName("JavaScript");
    engine.getContext().getBindings(ScriptContext.GLOBAL_SCOPE).put ("testMap", map);
    engine.eval("testMap.remove('key');");
    Assert.assertEquals (0, map.size());
}