Get indexOf?

Having trouble getting the index of an array item.

create ()
{
this.row = [1, 0, 1, 0, 0, 0];
for(var i = 0; i < this.row.length; i++){
var x = 150 + (i * 40);
if(this.row[i] ===1){
let cell = this.add.circle(x, 100, 10, 0xffffff).setInteractive();
cell.on(‘pointerdown’, function(){

                **let idx = indexOf(this.row[i]);**
                console.log(idx);
                
            });
        }

    }

I’d avoid using this as much as possible until you understand context and a bunch of very specific JS stuff.

The gist of it is that when you wrote function(){/** code here **/}, this is no longer what you think it is.

potential fixes: declare idx outside the function, consider using arrow functions, or, if you don’t use this.row elsewhere, use const instead.

If you do want to use this, consider reading You Don’t Know JS: Scope & Closures.

Thank you, but I still can’t get it to work. Can you give me an example of working code?

I’d need a https://codepen.io/ with your actual game, otherwise I’m just guessing. But maybe

create(){
  const rows = [1,0,1,0,0,0];
  for(let i = 0; i < rows.length; i+=1){
   // ... more code
   let idx = i; // i is the index that you want, right?
  cell.on('pointerdown', () => {
   // ... more code
  }
   // ... more code
}

Again, I am just guessing here so can you please make a codepen?

For the array method, it needs to be

arr.indexOf(search)

Hrm, I still can’t get this to work. There is no need for a codepen, this is the entire code. It just returns (-1) for the index no matter what I try:

class GameScene extends Phaser.Scene{
    constructor(){
        super({key: 'GameScene'}); 
    }
preload ()
{
}

create ()
{   
    var row = [1, 0, 1, 0, 0, 0];
        for(var i = 0; i < row.length; i++){
        var x = 150 + (i * 40);
            var cell = this.add.circle(x, 100, 10, 0xffffff).setInteractive();
            cell.on('pointerdown', ()=> {
             var  idx = row.indexOf(cell);  //tried "i" as well, both give -1
                console.log(idx);
            });
            

    }

}

Another way to put this. The problem is the individual cell.on does not treat the selected cell as an individual object with an index. Is there a way to get the index of the clicked on cell? (one way would be to get the x/y co-ordinates of the clicked cell and convert that back into the index number, which seems to be the way used by Emanuele Feronato in his tutorials… is there another way? )

var row = [1, 0, 1, 0, 0, 0];

for(var i = 0; i < row.length; i++){

   var x = 150 + (i * 40);
   var cell = this.add.circle(x, 100, 10, 0xffffff).setInteractive();
  console.log(i);   //this is correct: logs 0, 1, 2, 3, 4, 5
  cell.i = i;
  console.log(cell.i); //this is correct: logs 0, 1, 2, 3, 4, 5
      cell.on('pointerdown', function() {
        console.log(cell.i); //always logs "5"   
    });

}

cell.on('pointerdown', function () {
  console.log(this.i);
});
1 Like