【发布时间】:2017-03-05 10:07:39
【问题描述】:
我有一个对象如下:
var obj = {
parentKey : {
nestedKey1 : value,
nestedKey2 : function () {
return parentKey + nestedKey2;
}
}
};
有没有办法在上述嵌套键值对之一中保存的函数中使用 parentKey 和 nestedKey1 和/或 nestedKey2 的实际名称中的值?
在我的实际场景中,keys 都是我希望用作for loop 标准的数值。
更新场景到问题
作为学习 JavaScript 的练习,我决定编写电梯系统的逻辑代码。为此,我制作了一个代表建筑物的对象,该对象包含每一层,嵌套在每一层中的是希望前往另一层的人数数据,如下所示:
var floorData = {
<floor number> : {
<people going to floor X> : <number of people>,
<people going to floor Y> : <number of people>,
peopleGoingUp : <formula that sums amount of people going up>,
peopleGoingDown : <formula that sums amount of people going down>
}
};
我想在每个 <floor number> 对象中包含一个属性,该属性通过公式将 peopleGoingUp 和 peopleGoingDown 的数量相加。要让这个公式按我的意图工作,我需要访问 <floor number> 名称,它是来自 peopleGoingUp 和 peopleGoingDown 公式中的数值。
到目前为止,这是我的工作示例,我在楼 theBuilding[2] 中包含了 peopleGoingUp 和 peopleGoingDown 公式。我希望将theParentKey 的手动输入值更改为等于父对象的名称。
// Total number of floors in building global object
var totalFloors = 3;
// Building object including amount of people waiting to take lift to other floors on each level of the building
var theBuilding = {
0 : {
1 : 2,
2 : 0,
3 : 1,
},
1 : {
0 : 1,
2 : 3,
3 : 2,
},
2: {
0 : 2,
1 : 1,
3 : 4,
goingUp : function () {
var sum = 0;
var theParentKey = 2; // this is supposed to be a direct reference to the parent object name to this nested object and thus equal to 2
for (i = 0; i <= totalFloors; i++) { // loop for total floors
if (i !== theParentKey && i >= theParentKey) {//sum if i isn't = this floor number and that i is greater than this floor number
sum += this[i]
}
};
return sum;
},
goingDown : function () {
var sum = 0;
var theParentKey = 2; // this is supposed to be a direct reference to the parent object name to this nested object and thus equal to 2
for (i = 0; i <= totalFloors; i++) { // loop for total floors from lowest
if (i !== theParentKey && i <= theParentKey) { //sum if i isn't = this floor number and that i is less than this floor number
sum += this[i]
}
};
return sum;
},
3 : {
0 : 0,
1 : 1,
2 : 4
}
};
console.log(theBuilding[2].goingUp()); // 4
console.log(theBuilding[2].goingDown()); // 3
【问题讨论】:
-
是的,可以。对象可以引用任何字段中的任何内容。
-
太好了,我该怎么做呢?我知道通过使用 this.nestedKey1 我可以访问 nestedKey1 的值,但是如何访问 nestedKey1 的名称
-
请将您的场景添加到问题中。
-
你想参考什么?物业名称?属性值?
-
是的,我认为您尝试完成的事情不可能without changing your data structure。 JavaScript 没有向上的关系。
标签: javascript object nested parent