Defining Objects
Jump to navigation
Jump to search
JSON File
var mainNav = [{
item: "Home",
url: "../index.html"
},
{
item: "Product Videos",
url: "../videos/index.php"
},
{
item: "Photo Gallery",
url: "../photogallery.html"
},
{
item: "Installation Instructions",
url: "../installation/index.html"
},
{
item: "Catalog Download",
url: "../catalog/index.html"
},
{
item: "Tradeshows",
url: "../tradeshow.html"
}
];
Function That Creates the Navigation and Calls it
function showMainNav(arr) {
var output = "<ul>";
var i;
for (i = 0; i < arr.length; i++) {
output += '<a href="' + arr[i].url + '">' + '<li>' + arr[i].item + '</li></a>';
}
if (elements.mainNavigation !== null) {
elements.mainNavigation.innerHTML = output + '</ul>';
} // end if
} // end showMainNav
showMainNav(mainNav);
Using For In Loop
The for in loop does not always display the array in the order typed HTML
<h2>My List</h2> <ul id="links"> </ul>
<script>
var info = {
"full_name": "Ray Villalobos",
"title": "Staff Author",
"links": {
"blog": "http://iviewsource.com",
"facebook": "http://facebook.com/iviewsource",
"youtube": "http://www.youtube.com/planetoftheweb",
"podcast": "http://feeds.feedburner.com/authoredcontent",
"twitter": "http://twitter.com/planetoftheweb"
}
};
var output = "";
for (key in info.links) {
// if the link has the key property
if (info.links.hasOwnProperty(key)) {
output += '<li>' + '<a href="' + info.links[key] +
'">' + key + '</a>' + '</li>';
}
}
var update = document.getElementById('links');
update.innerHTML = output;
</script>
Object create
var john = {
name: 'John',
lastName: 'Smith',
yearOfBirth: 1990,
job: 'Teacher',
isMarried: false,
family: ['jane', 'mark'],
calculateAge: function() {
return 2016 - this.yearOfBirth;
}
};
console.log("--- " + john.calculateAge());
Loop through items
for(var item in john ){
console.log(item + " - " + john [item]);
Create an Object with a calculated value within the object
this will create the john.age with the calculated value
var john = {
name: 'John',
lastName: 'Smith',
yearOfBirth: 1990,
job: 'Teacher',
isMarried: false,
family: ['jane', 'mark'],
calculateAge: function() {
this.age = 2016 - this.yearOfBirth;
}
};
Creating a new Object for the john object
var harry = Object.create(john);