我正在尝试编写一个JavaScript函数,该函数接受下面的对象作为参数,并返回一个包含以下列的HTML表:“First Name”,“Last Name”,“Age”,“Color”。该表应该有4行。空值应显示为“n / a”。
var _data = [{
first_name: "John",
last_name: "Doe",
age: "40",
color: "Blue"
}, {
first_name: "Jane",
last_name: "Doe",
age: "38",
color: "Pink"
}, {
first_name: "Jack",
last_name: "Doe",
age: "10",
color: null
}, {
first_name: "Jill",
last_name: "Doe",
age: "8",
color: null
}];
到目前为止,在我的搜索中,我找不到处理像上面那样格式化的对象数组的示例。请注意整个数据数组是如何括在括号中的。
任何人都可以帮忙或指出一个例子吗?
第2部分
好的已经做了一些搞乱,这是我到目前为止(尝试仅使用Javascript)
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
</head>
<body>
<div id="tableContainer"></div>
<script>
window.onload = showData;//a call to the function to load the data..could add onload to body tag instead
var _data = [{
first_name: "John",
last_name: "Doe",
age: "40",
color: "Blue"
}, {
first_name: "Jane",
last_name: "Doe",
age: "38",
color: "Pink"
}, {
first_name: "Jack",
last_name: "Doe",
age: "10",
color: null
}, {
first_name: "Jill",
last_name: "Doe",
age: "8",
color: null
}]; //new array of objects.
function showData()
{
//a function to see if has value, if it does then display the value, if not then display n/a.
function checkForVal(val) {
return val || 'n/a';
}
var str;
str = "<table>";
str += "<tr><th>First Name</th><th>Last Name</th><th>Age</th><th>Favorite Color</th></tr>";
for (var i = 0; i < _data.length; i++) {
var brows = _data[i];
str += "<tr><td>" + checkForVal(brows.first_name) + "</td><td>" + checkForVal(brows.last_name) + "</td><td>" + checkForVal(brows.age) + "</td><td>" + checkForVal(brows.color) + "</td></tr>";
}
str += "</table>";
var tableReady = str;
var tableContainer = document.getElementById("tableContainer");
tableContainer.innerHTML = tableReady;
}
</script>
</body>
</html>
这有效,但我真的希望找到一个更好的解决方案,一个更面向OOP或更好的脚本。我想再次将这个对象数组(按原样)传递给一个函数,然后将该数据解析成一个表。如果有人想要更好地做到这一点,我将不胜感激。
答案 0 :(得分:0)
这是一个对象数组。
您可以访问此类元素
_data[0]["first_name"] // will give you "John"
依旧......