未定义不是 foreach 循环的函数

问题描述

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

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()
    }

}

解决方法

您基本上是在提供 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()
    }

}