在 QML 中声明 JS-dict 时如何使用 JS 数组作为键
How to use JS Arrays as keys when declaring JS-dicts in QML
在QML JS实现中,我可以这样写:
property var dict1: ({})
property var dict2: { 'a':1, 'b':2, 'c':3 }
// property var dict3: { [0,0]:1, [1,4]:5, [2,4]:3 } // can't do this!
// but can do this.
Component.onCompleted: {
dict1[[0,0]] = 1
dict1[[1,4]] = 5
dict1[[2,4]] = 3
}
所以最后一部分使用 JS-Arrays 作为字典中的键。然而,第 3 行 (dict3) 中的声明是不可能的。我不明白,如果可以通过其他方式获得预期结果,为什么不能使用一种表示法。
所以我的问题是:如何在不需要 Component.onCompleted
或类似 hack 的情况下实例化 dict
?
如果没有办法做到这一点,将不胜感激。
JS 对象键总是字符串。没有数组作为键或对象作为键这样的东西。
dict1[[0,0]] = 1
is strictly equivalent to dict1['0,0'] = 1
.
底线是 属性 分配和 属性 访问自动将密钥转换为字符串。
尝试以下操作:
dict1[dict2] = 42
console.log(JSON.stringify(dict1))
Output: {"0,0":1,"1,4":5,"2,4":3,"[object Object]":42}
表达式 dict2
被转换为其字符串表示形式并用作键。然后,您可以使用以下任一方法访问值 42
dict1["[object Object]"]
dict1[dict2]
dict1[dict1]
因为 toString(dict1)
returns "[object Object]"
dict1[({})]
因为 toString(({}))
returns "[object Object]"
这些强制转换在对象创建时的执行方式不同,这意味着您不能这样做 property var dict2: { [1,2]:3 }
。但是,property var dict2: { "1,2":3 }
将正常工作。
在QML JS实现中,我可以这样写:
property var dict1: ({})
property var dict2: { 'a':1, 'b':2, 'c':3 }
// property var dict3: { [0,0]:1, [1,4]:5, [2,4]:3 } // can't do this!
// but can do this.
Component.onCompleted: {
dict1[[0,0]] = 1
dict1[[1,4]] = 5
dict1[[2,4]] = 3
}
所以最后一部分使用 JS-Arrays 作为字典中的键。然而,第 3 行 (dict3) 中的声明是不可能的。我不明白,如果可以通过其他方式获得预期结果,为什么不能使用一种表示法。
所以我的问题是:如何在不需要 Component.onCompleted
或类似 hack 的情况下实例化 dict
?
如果没有办法做到这一点,将不胜感激。
JS 对象键总是字符串。没有数组作为键或对象作为键这样的东西。
dict1[[0,0]] = 1
is strictly equivalent todict1['0,0'] = 1
.
底线是 属性 分配和 属性 访问自动将密钥转换为字符串。
尝试以下操作:
dict1[dict2] = 42
console.log(JSON.stringify(dict1))
Output: {"0,0":1,"1,4":5,"2,4":3,"[object Object]":42}
表达式 dict2
被转换为其字符串表示形式并用作键。然后,您可以使用以下任一方法访问值 42
dict1["[object Object]"]
dict1[dict2]
dict1[dict1]
因为toString(dict1)
returns"[object Object]"
dict1[({})]
因为toString(({}))
returns"[object Object]"
这些强制转换在对象创建时的执行方式不同,这意味着您不能这样做 property var dict2: { [1,2]:3 }
。但是,property var dict2: { "1,2":3 }
将正常工作。