对象属性中的&符号 [英] Ampersand in object's properties
问题描述
我正在编写一个 JS 脚本,该脚本的某些属性中带有 &'s 的对象,例如
I'm writing a JS script that has an object with &'s in some of its properties, e.g.
var topicObj = {
"Client & Peripherals": ["USB", "Printer", "Copy/Paste"],
"Install & Upgrade": ["Tenant Upgrade", "Agent upgrade"]
}
问题是,当我尝试迭代其值之一时,例如
The thing is, when I attempt to iterate over one of its values, e.g.
selMTopic = "Client & Peripherals"
for (t in topicObj[selMTopic]) {
addTopic(topicsDD,topicObj[selMTopic][t]);
}
它失败了,它无法计算t,我猜它不喜欢在属性中包含 & 和类似字符.
it fails, it can't compute t, I guess it doesn't like having &'s, and similar characters, in the property.
我一直试图找出如何在没有运气的情况下在属性中拥有和使用 &'s;我试过用 encodeURIComponent 对字符串进行编码,但也没有运气.
I've been trying to find out how to have and use &'s in properties with no luck; I've tried encoding the string with encodeURIComponent but no luck either.
如果可能的话,我知道该怎么做吗?我需要那些&'s在那里.我认为它使用两个数组而不是对象,一个具有对象的属性,另一个具有对象的值数组;但我真的宁愿坚持使用一个对象,因为我可能需要添加更多深度级别";未来.
Any idea how can I do it, if possible? I need to have those &'s there. I'm thinking it using two arrays instead of the object, one with the object's properties, and the other each of the object's value arrays; but I would really rather stick with an object, as I may need to add more "levels of depth" in the future.
推荐答案
使用of(对于数组)而不是in(对于属性)
use of (for array) instead of in (for properties)
var topicObj =
{ "Client & Peripherals" : ["USB", "Printer", "Copy/Paste"]
, "Install & Upgrade" : ["Tenant Upgrade", "Agent upgrade"]
}
for (let selMTopic in topicObj)
{
for (let t of topicObj[selMTopic])
{
console.log( selMTopic,'->', t )
// addTopic(topicsDD, t );
}
}
这篇关于对象属性中的&符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!