如果您希望document.createElement
像在问题中那样使用,最简单的方法可能是这样的:
function generateTable(o) {
var table, tr, td, i, j, l, keys;
table = document.createElement('table')
for(i in o){
tr = document.createElement('tr');
table.appendChild(tr);
td = document.createElement('td');
keys = Object.keys(o[i]);
td.rowSpan = keys.length;
td.textContent = i;
tr.appendChild(td);
x=0;
for(j=0;j<keys.length;j++) {
if(j) {
tr = document.createElement('tr');
table.appendChild(tr);
}
td = document.createElement('td');
td.textContent = keys[j];
tr.appendChild(td);
td = document.createElement('td');
td.textContent =o[i][keys[j]];
tr.appendChild(td);
}
}
return table;
}
CAVEAT:Object.keys
在旧版浏览器中不可用,因此您需要这样的 polyfill:
(取自MOZILLA 开发者网络)
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
};
})();
}
或者,有一个更简单的 polyfill 可以很好地涵盖大多数情况:
(取自令牌帖子)
if (!Object.keys) Object.keys = function(o) {
if (o !== Object(o))
throw new TypeError('Object.keys called on a non-object');
var k=[],p;
for (p in o) if (Object.prototype.hasOwnProperty.call(o,p)) k.push(p);
return k;
}
你可以在这里看到它的作用:http: //jsfiddle.net/uyJv2/