我找不到任何能够清楚地解释错误和我应该做什么的事情.
我有这个数组:
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字符串.为什么?我该怎么办?我想在页面循环中使用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: "/",{ url: "/recordings",page: 'pages/recordings.html',{ url: "/editions",{ url: "/videos",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; }