繁体   English   中英

创建动态表并使用对象/数组填充-仅JavaScript

[英]Create a dynamic table and poplate with an object/array- JavaScript only

我正在尝试编写一个JavaScript函数,该函数接受以下对象作为参数,并返回包含以下列的HTML表:“名字”,“姓氏”,“年龄”,“颜色”。 该表应具有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或编写更好的脚本。 再次,我想将此对象数组(按原样)传递给一个函数,然后将数据解析为表。 如果有人想让它变得更好,那将不胜感激。

它是一个对象数组。

您可以像这样访问元素

_data[0]["first_name"] // will give you "John"

等等 ..

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM