首页 > 解决方案 > undefined 不是函数 foreach 循环

问题描述

我想为数组中的每个项目运行一个函数。数组每次都不同,但为此我将只使用一个示例数组。它一直说未定义不是函数,我假设未定义是foreach函数。这有什么解决办法?

const bar1beats = [0.5, 1, 2.5]
generate.addEventListener('click', generateclick)


function generateclick(){

// error line
  bar1beats.forEach(foreachfunction());

    function foreachfunction(item, index){

    let interval = intervals[Math.floor(Math.random() * intervals.length)]
    interval();
    if(interval == fifthfunction){
    findnotefifth()
    }
    if(interval == fourthfunction){
    findnotefourth()
    }

}

标签: javascriptfunctionforeach

解决方案


你基本上是在给予forEach undefined而不是你的功能。正如你所说,什么将传递foreachfunction.

要修复它,请删除括号:


function generateclick(){

  // note I removed the parenthesis.
  bar1beats.forEach(foreachfunction);

    function foreachfunction(item, index){

    let interval = intervals[Math.floor(Math.random() * intervals.length)]
    interval();
    if(interval == fifthfunction){
    findnotefifth()
    }
    if(interval == fourthfunction){
    findnotefourth()
    }

}

推荐阅读