0

I'm trying to write a JavaScript function that accepts the object below as a parameter and returns a HTML table with the following columns: "First Name", "Last Name", "Age", "Color". The table should have 4 rows. Null values should be displayed as "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
}];

In my searches so far I am not finding an example that deals with an object array formatted like the above. Notice how the entire data array is enclosed in brackets.

Can anyone help with this or point to an example?


Part 2

OK have done some messing around and here is what I have so far (trying to use Javascript only)

<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>

This works but I was really hoping to find a better solution one that is more OOP oriented or scripted better. Again I would like to pass this array of objects (as is) to a function that then parses the data into a table. If someone wants to take a stab at making this better It would be much appreciated.

4

1 回答 1

0

它是一个对象数组。

您可以像这样访问元素

_data[0]["first_name"] // 会给你“John”

等等 ..

于 2013-08-12T19:30:37.747 回答