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

4

我有一个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个回答

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());
}

太棒了!谢谢。 - Sarah Phillips

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接