首页 > 解决方案 > 我有一个可统一的数组,它是通过从服务器获取数据创建的

问题描述

我创建的数组无法在控制台上正确显示,我无法对其进行迭代。

我从 NodeJs 服务器获取一些数据,并通过一个类创建对象。喜欢:

 const listBooks = async function() {
        await fetch("/listBooks",{
            method: 'POST',
            headers: {
                'Content-Type': 'application/JSON'
            }
        }).then((res) => res.json())
        .then(data => {
            for(let book of data) new createBook(book,heads).addtoTable()
        })
    }()

“heads”是一个数组,使我能够检查书籍的属性是否与我确定的属性匹配,因为我将它们打印在表格中。

在这个类中(在 addtoTable() 函数中),我还通过“push”方法将“book”对象添加到另一个名为“books”的数组中。但是在脚本结束时,当我尝试打印“书籍”数组时,我得到了这样一个可统一的数组:

在此处输入图像描述

不像这样( Array(array length) [items] ) 在此处输入图像描述

当我尝试遍历 for...in 或 for...of 循环时,我什么也没得到。我该如何解决这个问题?

班上:

class createBook {
        constructor (book, heads) {
            this.book = new Object
            this.list = list
            for (let pm in book) {
                if(heads.find(({code}) => code === pm)) this.book[pm] = book[pm]
            }
        }

        addtoTable () {
            books.push(this.book)
            
            const bookListCon = document.querySelector(".bookListCon .bookList")
    
            var line = document.createElement("div")
            line.classList.add("listLine")
            line.setAttribute("id",this.book.id)
            
            for (const head of heads) {
                if (!head.show) continue
                var cell = document.createElement("div")
                cell.classList.add("listCell")
                var span = document.createElement("span")
                span.innerText = (this.book[head.code].length > 20) ? this.book[head.code].substring(0,20) + "..." : this.book[head.code]
                span.setAttribute("title",this.book[head.code])
                cell.appendChild(span)
                line.appendChild(cell)
            }
            
            bookListCon.appendChild(line)
            
            const addUpdate = document.querySelectorAll(".form_addBook .fline > input")
            line.addEventListener("click",()=>{
                for(let input of addUpdate) {
                    input.value = this.book[input.getAttribute("id")]
                }
                document.querySelector(".form_addBook .fListBox header").innerText = this.book.bookList
                document.querySelector("#control_addBook").checked = true
                
                var change = new Event("change")
                fCheck.dispatchEvent(change)

            })
        }
    }

标签: javascriptarraysclassasync-awaitfetch

解决方案


推荐阅读