【发布时间】:2020-11-18 10:22:02
【问题描述】:
所以...根据控制台,我遇到的问题是: “未捕获的类型错误:无法读取未定义的属性“标题” 在 custom.js:42,在 Array.forEach (),在 custom.js:39"
“标题”如何未定义?我的 .forEach 有什么问题? (悲伤的声音)
我构建的 JSON 数组中六个对象中的第一个示例:
var newReleases = [
{
"title":"Honor - Defending the motherland",
"author":"Mark Thomas",
"genre":"Fiction",
"description":"In legislation and formal documents the suffix shire was generally not used: for example, Bedfordshire was referred to as the administrative county of Bedford and the Northamptonshire council as the county council of Northampton.The 1888 Act did not contain a list of administrative counties: it was not until 1933 and the passing of a new Local Government Act."},
带有 forEach 函数的 For 循环:
for (var i = 0; i < 6; i++){
newReleases.forEach (function (newReleases) {
var bookTitle = document.getElementsByClassName('card-header')
var t = document.createTextNode(newReleases[i].title);
bookTitle.appendChild(t);
var bookAuthor = document.getElementsByClassName('card-title')
var a = document.createTextNode(newReleases[i].authors);
bookAuthor.appendChild(a);
var cardGenre = document.getElementsByClassName("card-subtitle");
var genre = document.createTextNode(newReleases[i].genre);
cardGenre.appendChild(genre);
var cardDescr = document.getElementsByClassName('card-text');
var p = document.createTextNode(newReleases[i].description);
cardDescr.appendChild(p);
}) //end of forEach
} // end of for-loop
【问题讨论】:
-
你不应该同时使用
for和foreach来循环同一个数组。 -
至于为什么你的引用是错误的,这很可能是因为传递给 forEach 的参数也被命名为
newReleases。那不是数组。 -
回调函数参数不要使用同一个变量
newReleases。这使它成为对象,而不是数组。 -
只是脱离逻辑,如果说
forEach(function(book){ ...会更有意义
标签: javascript arrays for-loop foreach typeerror