Kotlin-JS互操作 – 使用语言结构

我有一个js互操作函数,它使用for in构造来迭代输入元素,但是它在运行时抛出错误。

 native("document") val ndoc: dynamic = noImpl fun jsInterOp() { js("console.log('JS inling from kotlin')") val ies = ndoc.getElementsByTagName("input") for (e in ies) { console.log("Input element ID: ${e.id}") } } 

获取以下js错误

 Uncaught TypeError: r.iterator is not a functionKotlin.defineRootPackage.kotlin.Kotlin.definePackage.js.Kotlin.definePackage.iterator_s8jyvl$ @ kotlin.js:2538 

任何建议如何解决这一个?

Kotlin:M12

为该函数生成的js代码是,

  jsInterOp: function () { var tmp$0; console.log('JS inling from kotlin'); var ies = document.getElementsByTagName('input'); tmp$0 = Kotlin.modules['stdlib'].kotlin.js.iterator_s8jyvl$(ies); while (tmp$0.hasNext()) { var e = tmp$0.next(); console.log('Input element ID: ' + e.id); } }, 

forEach没有工作,因为它是JS中的Array函数,但getElementsByTagName返回HTMLCollection 。 所以我改变了kotlin代码,使用传统的for循环迭代这个集合,并按预期工作。

  val ies = ndoc.getElementsByTagName("input") for (i in 0..(ies.length as Int) - 1) { console.log("InputElement-${i} : ${ies[i].id}") } 

Kotlin for-loop使用了很多内在的魔法。 forEach()在JS上更直接。 尝试这个:

 ies.iterator().forEach { ... } 

这似乎是Kotlin M12中的一个bug,因为即使在简单的列表中我也无法做一个for-loop。

 for(i in listOf(1, 2)); // TranslationInternalException 

我不确定你在这里使用的是什么document ,但你可能会喜欢标准的API:

 import kotlin.browser.document val ies = document.getElementsByTagName("input")