出于某种原因,在 currentRow.cells 下面的代码中返回 {}。我该如何检查呢?如果 currentRow.cells 返回 {},我不想执行行。
currentRow = document.createElement("TR");
if(currentRow.cells.length > 0) { .. do something }
更新 1:
我想要的只是检查空对象。如果 currentRow.cells 是一个空对象,则什么也不做。
出于某种原因,在 currentRow.cells 下面的代码中返回 {}。我该如何检查呢?如果 currentRow.cells 返回 {},我不想执行行。
currentRow = document.createElement("TR");
if(currentRow.cells.length > 0) { .. do something }
更新 1:
我想要的只是检查空对象。如果 currentRow.cells 是一个空对象,则什么也不做。
我总是得到一个 HTMLCollection 类型的对象。
然后,您应该能够使用如下代码检查集合的长度:
if(currentRow.cells.length != 0) {
//row and cells exist, work with them
}
jQuery 有一个名为$.isEmptyObject().
他们的代码很简单:
function isEmptyObject( obj ) {
for ( var name in obj ) {
return false;
}
return true;
}
如果您不想使用整个 jQuery 库,您可以使用此方法并将其放在您自己的代码库中的某个位置!
currentRow是 a <tr>(或 a HTMLTableRowElement),并且currentRow.cells是 a HTMLCollection(不是数组 ( []) 或对象 ( {}))。
如果currentRow.cells未定义,则表示该current行不是 a <tr>,而是另一个元素。
要检查 DOM 元素是否为空,您可以使用childNodes(this will never be undefined)。
if(currentRow.childNodes.length === 0){
// empty
}
else{
// not empty
}
编辑:更好的是,您可以使用hasChildNodes.
if(!currentRow.hasChildNodes()){
// empty
}
else{
// not empty
}
cells<tr>属性在 IE8 及更低版本中不可用。按照上面的建议进行锻炼childNodes。以下代码检查是否cells未定义:
var currentRow = document.createElement("TR");
if (typeof currentRow.cells === "undefined") {
// use currentRow.childNodes
}
else {
// use currentRow.cells
}
要在标题中回答您的问题:
function is_empty(obj) {
for(var i in obj) {
if(obj.hasOwnProperty(i))
return false;
}
return true;
}
alert(is_empty({})); // true