0

I'm trying to get array index by value.

I have this code:

var squares = new Array();
for (var i = 1; i <= 160; i++) {
    squares.push(i);
}

angular.element('.click').click(function () {
    var squareId = angular.element(this).attr('id');
    var fisk = squares.indexOf(squareId);
    console.log(fisk);
});

This only returns -1, thus, It can't be found. If a replace squareId with a number in indeOf, it works perfect, but if I use a variable, It don't work.

Anyone who can help me?

Chris Martin
  • 30,334
  • 10
  • 78
  • 137
user500468
  • 1,183
  • 6
  • 21
  • 36

2 Answers2

2

You are initializing your array values with numbers between 1 and 160, so squares.indexOf(1) for example would return 0.

What you want to do is initialize the array with the actual ids of your elements.

georgehdd
  • 433
  • 3
  • 12
1

See Example Fiddle

It's because the variable squareId could be returning a string value. The function indexOf can't find the string because it has numbers in the array.

// string search
var squareId = '2';
var fisk = squares.indexOf(squareId);
console.log('This will not be found ' + fisk);

// number search
var squareId = Number('2');
var fisk = squares.indexOf(squareId);
console.log('This will be found ' + fisk);

See similar question

Community
  • 1
  • 1
khakiout
  • 2,372
  • 25
  • 32