假设我有一个记录数据库,此处称为 recordDOM
,并且我需要分割其长度以适应特定的大小限制。
以下代码片段不起作用。它产生一个 TypeError: TypeError: packet[packetCount] is undefined
var packet = {};
var packetCount = 0;
var elementCount = 0;
$.each(recordDOM, function(index, element) {
if (elementCount >= 168) {
packetCount++;
elementCount = 0
}
if (typeof element != "undefined") {
packet[packetCount][elementCount] = element;
}
elementCount++;
});
我已经尝试将packet
变量初始化为数组,并对上面的代码进行了一些其他小的编辑,但我显然遗漏了一些东西。可以请您赐教吗?
[编辑]所需的输出是:
packet = {
"0": {
"0": {
// First Element
},
"1": {
// Second Element
},
...
"167": {
// Last element of the first packet
}
},
"1": {
"0": {
// First Element of the second packet
},
"1": {
// Second Element
},
...
"167": {
// Last element of the second packet
}
}
}
最佳答案
你只需要初始化内部对象,
var packet = {};
var packetCount = 0;
var elementCount = 0;
$.each(recordDOM, function(index, element) {
if (elementCount >= 168) {
packetCount++;
elementCount = 0
}
if (element != undefined) {
if(!packet[packetCount]){
packet[packetCount] = {}; // Change is here
}
packet[packetCount][shipCount] = element;
}
shipCount ++;
});
关于Javascript 对象数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42760142/