-1

I would like to have a function run for every item in an array. The array is different every time but for this I will just use an example array. It keeps saying undefined is not a function at the, I assume undefined being foreachfunction. Whats the solution to this?

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

}
Arlo Erwin
  • 19
  • 1
  • Don't call the function? Why not instead just pass it in? `bar1beats.forEach(foreachfunction);` – evolutionxbox May 11 '21 at 16:54
  • 2
    _" I assume undefined being foreachfunction"_ - That would be easy to check with some basic debugging, and should have been done _before_ asking us. – Andreas May 11 '21 at 16:55
  • Looks like you already know the solution, because it's the same as in: `.addEventListener('click', generateclick)` – Andreas May 11 '21 at 16:56

1 Answers1

0

You are basically giving forEach undefined instead of your function. As you call it what will pass the return value of foreachfunction.

To fix it remove the parenthesis:


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

}
Sifat Moonjerin
  • 180
  • 1
  • 12
midugh
  • 608
  • 5
  • 21