2017-09-26 5 views
4

私はスクリプトエンジンに渡したJava HashMapを持っています。後で無効なキーを報告しているので、処理されているエントリを削除したいと思います。エントリを削除するための明らかな通常の方法(delete testMap['key'];)は効果がありません。Nashorn JavaScript内からJava Mapから要素を削除する方法

このテストに合格するにはどうすればよいですか?

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

答えて

3

あなたがHashMapを持っていることがわかっている場合、あなたは:すなわち、そのMap APINashorn

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

パーフェクトを使用することができます!ありがとうございました。 –

関連する問題