我有一个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 中的一个错误,因为即使在简单的列表中我也无法执行 for 循环。
for(i in listOf(1, 2)); // TranslationInternalException
也
我不确定您在这里使用的document
是什么,但您可能喜欢标准 API:
import kotlin.browser.document
val ies = document.getElementsByTagName("input")