我有一个代码,其中我通过使用new Array()创建了二维数组;这是我的代码,我在其中从一些REST api获取一些值,并像下面的代码所示那样操纵这些值
我尝试使用堆栈溢出的可用帮助来迭代我正在创建的对象,以解决其他用户先前发布的问题,即尝试使用键值对来迭代数组,使用foreach循环或使用对象语法中的键使用For循环。
var CCTVCounterDictionary = new Array();
var InitCCTVCounter = function (type, zoneName, quantityCCTV) {
if (CCTVCounterDictionary[type] == undefined) {
CCTVCounterDictionary[type] = new Array();
if (CCTVCounterDictionary[type][zoneName] == undefined) {
CCTVCounterDictionary[type][zoneName] = new CCTVCounter(type, zoneName, 0);
CCTVCounterDictionary[type][zoneName].Increment(quantityCCTV);
}
}
else if (CCTVCounterDictionary[type][zoneName] == undefined) {
CCTVCounterDictionary[type][zoneName] = new CCTVCounter(type, zoneName, 0);
CCTVCounterDictionary[type][zoneName].Increment(quantityCCTV);
}
else {
CCTVCounterDictionary[type][zoneName].Increment(quantityCCTV);
}
};
这是我的js类,用于调用对象CCTVCounter的Increment函数,该对象已分配给数组每个第二维的字符串索引
function CCTVCounter(type, zon, counter) {
this.CCTVType = type;
this.ZoneName = zon;
this.CCTVCount = counter;
}
CCTVCounter.prototype.Increment = function (incrementBy) {
if (incrementBy == undefined)
this.CCTVCount++;
else
this.CCTVCount += parseInt(incrementBy);
}
这种方法的问题是我的数组长度保持为0,并且如果我尝试使用foreach迭代数组,则似乎无法使用foreach循环或for循环语法在CCTVCounterDictionary中找到键。
我正在尝试为一段代码寻求帮助,以便能够如上图所示迭代此数组,但是我无法弄清楚如何实现。任何帮助都将受到高度赞赏。
下面,我将包括有关创建二维数组的代码如何呈现输出的日志
SmartEnforcement.js: 202[] Banjir: Array(0) undefined: CCTVCounter {
CCTVType: "Banjir",
ZoneName: undefined,
CCTVCount: 264
}
length: 0 __proto__: Array(0) Cadangan: Array(0) undefined: CCTVCounter {
CCTVType: "Cadangan",
ZoneName: undefined,
CCTVCount: 26
}
length: 0 __proto__: Array(0) Sediada: Array(0) PJS: CCTVCounter {
CCTVType: "Sediada",
ZoneName: "PJS",
CCTVCount: 368
}
PJU: CCTVCounter {
CCTVType: "Sediada",
ZoneName: "PJU",
CCTVCount: 981
}
SEKSYEN: CCTVCounter {
CCTVType: "Sediada",
ZoneName: "SEKSYEN",
CCTVCount: 504
}
SS: CCTVCounter {
CCTVType: "Sediada",
ZoneName: "SS",
CCTVCount: 816
}
length: 0 __proto__: Array(0) length: 0 __proto__: Array(0)
这是我调用主函数以调用InitCCTVCounter的方式
InitCCTVCounter(marker.Type, f.attributes.ZON, marker.TotalCCTVS);
答案 0 :(得分:0)
您创建的不是数组而是jSon对象。 使用Object.keys循环遍历其键 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
答案 1 :(得分:0)
我认为您构建2d数组的逻辑很复杂。我建议在对象上使用 foreach 。
要迭代对象,如下所示
select
a.*,
b.*,
d1.x as x,
d2.x as y
from
a
join
b on a.id = b.id
join
d as d1 on d.id = b.id
join
d as d2 on d.id <> b.id
使用其中的 CCTVCounterDictionary.push 构建阵列。