我在运行代码时遇到此控制台错误:
未捕获的TypeError:无法读取未定义的属性'length'
完整日志
at renderUserBlocks (eval at globalEval (jquery.min.js:2), <anonymous>:692:47)
at Object.success (eval at globalEval (jquery.min.js:2), <anonymous>:242:17)
at i (jquery.min.js:2)
at Object.fireWith [as resolveWith] (jquery.min.js:2)
at z (jquery.min.js:4)
at XMLHttpRequest.<anonymous> (jquery.min.js:4)
我的代码
function renderUserBlocks(blocksResults){
var $blocksRows = $('#blocks_rows');
for (var i = 0; i < blocksResults.length; i += 2){
var block = parseUserBlock(blocksResults[i + 1], blocksResults[i]);
var blockJson = JSON.stringify(block);
var existingRow = document.getElementById('blockRow' + block.time);
if (existingRow && existingRow.getAttribute('data-json') !== blockJson){
$(existingRow).replaceWith(getUserBlockRowElement(block, blockJson));
$('[data-toggle="tooltip"]').tooltip();
}
else if (!existingRow){
var blockElement = getUserBlockRowElement(block, blockJson);
var inserted = false;
var rows = $blocksRows.children().get();
for (var f = 0; f < rows.length; f++) {
var pTime = parseInt(rows[f].getAttribute('data-time'));
if (pTime < block.time){
inserted = true;
$(rows[f]).before(blockElement);
break;
}
}
if (!inserted)
$blocksRows.append(blockElement);
$('[data-toggle="tooltip"]').tooltip();
}
}
}
此行显示错误
for (var i = 0; i < blocksResults.length; i += 2)
答案 0 :(得分:1)
这是因为blocksResults
是null
,并且它没有length
属性。
您可以在for循环之前检查它
if (blocksResults) {loop here}