【发布时间】:2021-08-10 19:16:06
【问题描述】:
const myBooks = [
{
title: 'Why We Sleep',
author: 'Matthew Walker',
},
{
title: 'All freinds',
author: 'Christian'
}
];
function createBookList(books) {
let list = document.createElement('ul');
books.forEach((sam) => {
let li = document.createElement('li');
let p = document.createElement('p');
let image = document.createElement('img');
image.src = 'https://media-amazon.com/7ov383lj3Rr';
p.textContent = `${sam.title} - ${sam.author}`;
li.style.listStyleType = 'none';
list.appendChild(li);
list.appendChild(p);
list.appendChild(image);
});
return list;
}
嘿,我正在尝试仅为数组的第一个对象添加图像,但它同时出现在图像的两个对象中。所以任何建议
【问题讨论】:
-
将
idx添加为forEach中的第二个参数并添加if (idx === 0) {...here add img...}。
标签: javascript arrays dom