javascript - 渲染数组对象列表(Javascript)
问题描述
我被困在一个功能中。我正在尝试呈现书籍列表- 这个列表是一个对象数组。但在将其呈现为 HTML 之前,我必须检查对象中是否存在所有三个属性,即作者、名称和价格,并且只呈现具有所有三个属性的对象。所以我用try...catch
. 然后我map()
用来创建新数组并渲染它。Try...catch
块检测到错误,但不显示没有错误的对象。这是我的代码:
function renderBooks(arr) {
const list = document.getElementById("root");
function makeElem(arrItem, arrIndex) {
const {author, name, price} = arrItem;
let li = document.createElement('li');
if (!author) {
throw new Error(`no author in book: #${arrIndex + 1}`);
} else if (!name) {
throw new Error(`no name in book: #${arrIndex + 1}`);
} else if (!price) {
throw new Error(`no price in book: #${arrIndex + 1}`);
}
return li.innerHTML = `<strong>Author:</strong> ${author}<br><strong>Name:</strong> ${name}<br><strong>Price:</strong> ${price}`;
}
arr.map((item, index) => {
try {
makeElem(item, index);
return list.innerHTML = `<ul>${makeElem(item)}</ul>`;
} catch (Error) {
console.log(Error);
}
});
}
renderBooks(books);
UPD:我已经更新了代码,现在只呈现第一本书,但所有其他符合条件的书籍都没有。
解决方案
我已经更新了你的实现来做我认为你想做的事情:-
function renderBooks(arr) {
const list = document.getElementById("root");
function makeElem(arrItem, arrIndex) {
const {author, name, price} = arrItem;
let li = document.createElement('li');
if (!author) {
throw new Error(`no author in book: #${arrIndex + 1}`);
} else if (!name) {
throw new Error(`no name in book: #${arrIndex + 1}`);
} else if (!price) {
throw new Error(`no price in book: #${arrIndex + 1}`);
}
li.innerHTML = `<strong>Author:</strong> ${author}<br><strong>Name:</strong> ${name}<br><strong>Price:</strong> ${price}`;
return li;
}
const listContainer = document.createElement('ul');
// Incase you don't know this, read about it. Helps from performance point of view for large DOM updates.
const listFragment = document.createDocumentFragment();
arr.forEach((item, index) => {
try {
const listElement = makeElem(item, index);
listFragment.append(listElement);
} catch (Error) {
console.log(Error);
}
});
listContainer.append(listFragment);
list.append(listContainer);
}
renderBooks(books);
您当前代码的方式 - 会有一定数量的问题。首先是考虑添加多个列表元素。设置innerHTML
你所做的方式肯定会覆盖以前添加的li
元素,你只会看到一个。在这里也.forEach
更有意义,.map
因为您不必返回新数组。
推荐阅读
- r - 在R中将两个输出表合二为一
- node.js - EACCES:权限被拒绝,mkdir '/node_modules/node-sass/build' 在 ubuntu 上运行 npm install 时
- node.js - 在nodejs中安装bycrpt时出错?每当我运行 npm install install --save 时?
- c# - 在数据库 Jquery 中添加 CheckBox 检查值
- vue.js - toggle class conditionally in Vue.js
- selenium - 自动化测试用例的行业标准是什么?
- spyder - 如何更新 Spyder 3.3.0
- reactjs - 如何配置 webpack2?
- c++11 - 如何获得 boost::mpl::map 的 *any* 示例?
- javascript - Formik & yup 表单验证无法在 VirtualizedSelect 中按预期工作