Javascript根据变量引用更改变量

标签 javascript

在我正在编写的程序中,我需要一个如下所示的对象变量:

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..inmore .

关于Javascript根据变量引用更改变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10462333/

相关文章:

javascript - 如何使我的网页随浏览器窗口调整大小

javascript - 如何根据字符第三次出现来剪切字符串?

Javascript 变量出现在控制台中但未定义

javascript - 获取指定索引处的 Accordion ID

javascript - jquery中如何获取li元素的点击事件?

javascript - 带有数据的 Handlebars.js 网格

javascript - 如何将对象属性传输到现有对象 JavaScript?

javascript - 在javascript中迭代数组+返回总和?

javascript - 我可以使用 ES2015 类扩展 Proxy 吗?

javascript - 如何克隆一个构造函数,以便它构造一个原始类型的副本,其行为与原始类型一样,但有自己的原型(prototype)?