在index-dev.html
中,我加载了一个本地JavaScript文件:
<script type="text/javascript" src="map.js"></script>
map.js
结构上(不是字面意思)看起来像这样:
var a2b = {
"a": "My life closed twice before its close—",
"b": "It yet remains to see",
"c": "If Immortality unveil",
"d": "A third event to me",
"e": "So huge, so hopeless to conceive",
"f": "As these that twice befell.",
"g": "Parting is all we know of heaven,",
"h": "And all we need of hell.",
"z": "Emily Dickinson, 1830-1886"
}
我想出了如何将这个对象加载到Scala.js中:
val a2b = js.Dynamic.global.a2b
现在a2b
的类型为Dynamic
。我想要的是Map[String,String]
。
我试过了:
val a2b = js.Dynamic.global.a2b.asInstanceOf[Map[String,String]]
但这不起作用。我该怎么做才能获得Map[String,String]
?
答案 0 :(得分:5)
关键是它不是一个Map
,这就是它无法正常工作的原因。但 是js.Dictionary
。因此,请将其用于asInstanceOf
,如果您确实需要Scala Map
,请使用toMap
函数:
val a2b = js.Dynamic.global.a2b.asInstanceOf[js.Dictionary[String]].toMap