Ayb*_*gür 1 javascript arrays qml qtquick2
显然,children属性被记录为a list<Item>,没有内置的Javascript indexOf(element).以下代码:
Item{
id: exampleParent
Item{ id: exampleChild }
}
Button{
text: "Get index"
onClicked: console.log(exampleParent.children.indexOf(exampleChild))
}
Run Code Online (Sandbox Code Playgroud)
会抛出TypeError: Property 'indexOf' of object [object Object] is not a function错误.
为什么会这样,有什么具体原因吗?有没有比手动遍历children阵列更好的解决方案?
米奇给出了一个很好的解释,为什么你不能直接打电话indexOf,但有一种方法间接地做.您可以使用call上Array.prototype.indexOf():
Row {
Item{
id: exampleParent
Item{}
Item{ id: exampleChild }
}
Button{
text: "Get index"
onClicked: console.log(Array.prototype.indexOf.call(exampleParent.children, exampleChild))
}
}
Run Code Online (Sandbox Code Playgroud)