I can't find anything that explains clearly what is wrong and what I should do.
I have this array:
const pages = [
{
url: "/",
page: 'pages/home.html',
title: "Home" },
{
url: "/recordings",
page:'pages/recordings.html',
title: "Recordings" },
{
url: "/editions",
page: 'pages/editions.html',
title: "Editions" },
{
url: "/videos",
page: 'pages/videos.html',
title: "Videos" },
]
I'm trying to loop it through with a for loop. page.url returns "undefined" in the console. But the "Test URL" console log returns a url string as expected. Why? What do I do? I want the page.url in the foor loop.
console.log("Pages: " + pages)
console.log("Test URL: " + pages[1].url)
for (page in pages) {
console.log("Page: " + page)
console.log("Page URL: " + page.url)
}
You could use a for ... of
statement, where you get the element of the array instead of the index by using a for ... in
statement.
const pages = [{ url: "/", page: 'pages/home.html', title: "Home" }, { url: "/recordings", page: 'pages/recordings.html', title: "Recordings" }, { url: "/editions", page: 'pages/editions.html', title: "Editions" }, { url: "/videos", page: 'pages/videos.html', title: "Videos" }];
for (var page of pages) {
console.log("Page: " + page.page);
console.log("Page URL: " + page.url);
}
.as-console-wrapper { max-height: 100% !important; top: 0; }
for..in is a method for iterating over "enumerable" properties of an object.
With arrays using for..in reveals the indexes:
const pages=[{url:"/",page:'pages/home.html',title:"Home"},{url:"/recordings",page:'pages/recordings.html',title:"Recordings"},{url:"/editions",page:'pages/editions.html',title:"Editions"},{url:"/videos",page:'pages/videos.html',title:"Videos"}]
for (let index in pages) {
console.log(index);
console.log(pages[index].page);
}
for..of can be used to iterate over "iterable" collections. This acts like a .forEach()
function:
const pages=[{url:"/",page:'pages/home.html',title:"Home"},{url:"/recordings",page:'pages/recordings.html',title:"Recordings"},{url:"/editions",page:'pages/editions.html',title:"Editions"},{url:"/videos",page:'pages/videos.html',title:"Videos"}]
for (let page of pages) {
console.log(page);
console.log(page.page);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With