如何从 Nashorn JavaScript 中的 Java Map 中删除元素
How to remove element from Java Map from within Nashorn JavaScript
我有一个 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());
}
如果你知道你有一个 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());
}
我有一个 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());
}
如果你知道你有一个 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());
}