我创建了一个对象,我存储了十六进制网格的各种属性。
我以x coord + y coord + z coord
hex.id = cX + "x" + cY + "y" + cZ + "z"; //where cX, cY and cZ are some numbers
// adding the hex to our hexList with the id as identifier
hexList[hex.id] = hex; //hex is a graphics object
但是,现在我无法检索hexlist对象。我确信这与我在id中输入的类型os名称有关。
当我创建它时,我想我只需拨打hexList.<some coord id>
并能够使用它。
我已附加我的控制台日志,可帮助您了解该问题。如何使用id(例如5x3y19z)来调用和使用我的hexList父对象中的对象?
> hexList
{0x0y0z: Object, 1x-1y0z: Object, 2x-2y0z: Object, 3x-3y0z: Object, 4x-4y0z: Object, 5x-5y0z: Object, 6x-6y0z: Object, 7x-7y0z: Object, 8x-8y0z: Object, 9x-9y0z: Object, 840 more…}
> hexList.10x-12y22z
SyntaxError: identifier starts immediately after numeric literal
我是JS新手,我确定我定义HexList的方式不合适。但我不知道那里有什么不对。
认为问题可能是将id作为数字,我稍微改了一下;
hex.id = "hex" + cX + "x" + cY + "y" + cZ + "z"; //where cX, cY and cZ are some numbers
// adding the hex to our hexList with the id as identifier
hexList[hex.id] = hex; //hex is a graphics object
这给了我答案;
> hexList
{hex0x0y0z: Object, hex1x-1y0z: Object, hex2x-2y0z: Object, hex3x-3y0z: Object, hex4x-4y0z: Object, hex5x-5y0z: Object, hex6x-6y0z: Object, hex7x-7y0z: Object, hex8x-8y0z: Object, hex9x-9y0z: Object, 840 more…}
> hexList.hex-10x-10y20z
SyntaxError: identifier starts immediately after numeric literal
> hexList.hex10x10y20z
undefined
很明显,问题是-
标志。但是我想因为这些都是id字符串的一部分,所以不应该有问题。
我知道我可以在代码中简单地使用"n"
/ "p"
后缀代替-
/ +
符号并使其正常工作,但我想知道我是否可以只需更改我调用对象的部分?
答案 0 :(得分:4)
hexList.10x-12y22z
// ^ That's not a valid character in property names
有你的问题。
JavaScript将其解释为:
hexList.10x - 12y22z;
显然,这是无效的JS。
用括号访问替换你的点符号,如下所示:
hexList['10x-12y22z']