Javascript 未捕获类型错误:topics.forEach不是函数

Javascript 未捕获类型错误:topics.forEach不是函数,javascript,Javascript,我试图获得数组的输出 document.addEventListener("DOMContentLoaded", function() { document.getElementById('button').addEventListener('click', function() { var sidebar = document.getElementById('sidebar'); var isExpanded = false; sidebar.classList.fo

我试图获得数组的输出

document.addEventListener("DOMContentLoaded", function() {
document.getElementById('button').addEventListener('click', function() {
    var sidebar = document.getElementById('sidebar');

    var isExpanded = false;
    sidebar.classList.forEach(function(className) {
        if (className == 'expand') {
            isExpanded = true;
        }
    });

    if (isExpanded) {
        sidebar.classList.remove('expand');
    } else {
        sidebar.classList.add('expand');
    }

    isExpanded = !isExpanded;



    var contentwrapper = document.getElementById('content-wrapper');


    if (isExpanded) {
        contentwrapper.classList.add('padding-offset-2');

    } else {
        contentwrapper.classList.remove('padding-offset-2');
    }


    var topics = document.getElementById("content-wrapper").children;
    console.log(topics);
    topics.forEach(function(topic) {

        console.log(topic);

    })

});
我得到一个错误,topics.forEach不是一个函数。有人能帮我吗?我不知道我做错了什么。我正在努力学习英语。:)

topics
是一个数组,而不是数组,因此没有forEach()方法。你需要先做

主题给出HTMLCollection的集合,将其转换为数组

看到这个了吗

因为每一个都不起作用。 尝试使用类作为选择器

$.each( topic, function( key, value ) {
  alert( key + ": " + value );
 // do your stuff here
});


请修复你的代码给我们你的
console.log(主题)的输出我假设您的
主题
不是一个数组。您试图遍历不存在的子项列表。您可以使代码类型安全并声明
topics&&topics.forEach
,但无论哪种方式,您的应用程序都毫无意义,无论是否由于类型错误而崩溃。
 var topics = document.getElementById("content-wrapper").children;
   console.log(topics);
  var topics= [].slice.call(topics);
$.each( topic, function( key, value ) {
  alert( key + ": " + value );
 // do your stuff here
});
$(".content-wrapper").each(function() {
  // do your stuff here
});