我找不到任何东西可以清楚地解释什么是错误的以及我应该做什么。
我有这个数组:
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 循环遍历它。 page.url 在控制台中返回“undefined”。但是“测试 URL”控制台日志按预期返回了一个 url 字符串。为什么?我该怎么办?我想要 foor 循环中的 page.url。
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)
}
最佳答案
你可以使用 for ... of
statement ,在这里您可以使用 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; }
关于javascript - 如何在 javascript 的 for 循环中访问对象属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50496080/