在我正在编写的程序中,我需要一个如下所示的对象变量:
var map {
cube: {__pt3arraylocation__:[0,0,0], poly: new Object()},
other: {__pt3arraylocation__:[1,0,0], poly: new Object()}
};
但是,我希望能够输入map.cube并让它返回pt3arraylocation作为默认值,除非我通过输入map.cube.poly指定我想要的内容
例如:map.cube 将返回 [0,0,0],map.cube.poly 将返回对象立方体中的对象 Poly
提前致谢
最佳答案
i want to be able to type map.cube and have it return the pt3arraylocation as a default unless i specify what i want by typing map.cube.poly
for example: map.cube would return [0,0,0] and map.cube.poly would return the object poly in the object cube
你不能在 JavaScript 中做到这一点。
但是,作为替代方案,值得注意的是,如果您愿意,您可以向数组添加任意属性。例如:
var map {
cube: [0,0,0],
other: [1,0,0]
};
map.cube.poly = {}; // {} is the same as `new Object()` but not subject to people...
map.other.poly = {}; // ...overriding the `Object` symbol
然后,map.cube
为您提供数组,map.cube.poly
为您提供存储在该数组中的对象。
这怎么可能?因为在 JavaScript 中,arrays aren't really arrays 。它们只是具有自动 length
属性的对象,以特殊方式处理一类属性名称(所有数字),并有 Array.prototype
支持它们。当然,您可以向任何对象添加属性。
没有文字语法可以执行此操作,这就是为什么我必须在上面的对象初始值设定项之后使用赋值来执行此操作。但这是完全有效的。我一直用它来交叉索引数组。
如果您这样做,请确保您没有错误地使用 for..in
; more .
关于Javascript根据变量引用更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10462333/