首页 > 解决方案 > 渲染数组对象列表(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:我已经更新了代码,现在只呈现第一本书,但所有其他符合条件的书籍都没有。

标签: javascriptarraysjavascript-objects

解决方案


我已经更新了你的实现来做我认为你想做的事情:-

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因为您不必返回新数组。


推荐阅读