0

I have a foreach loop for an array, with an index to tell me which loop i am on, and an item to tell me the value of the loop i am on. Probably an obvious answer, but I'd like to be able to get the item from the index. How might i do this?

const bar1beats = [1, 0.5, 0.5, 2]

bar1beats.forEach(foreachfunction);

function foreachfunction(item, index1){

checkitemof(index1 - 1)

}
  • Can you provide a [mcve] that shows what precisely you're trying to do? `forEach` might not be the optimal method. – Andy Apr 04 '22 at 16:07

1 Answers1

0

The forEach function callback can accept three arguments - the item, the index, and the array itself.

function foreachfunction(item, index1, theArray){
    if (index1 > 0) {
        const previousItem = theArray[index1 - 1];
        ...
    }
}
Richard Deeming
  • 29,830
  • 10
  • 79
  • 151