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?

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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

3 Comments

How can I convert all my numbers in the array to string?
like this squares.push('' + i); or i.toString() :) @user500468

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.