-3

I have a long array of strings with page IDs; when the current page ID matches one from the array, stuff needs to happen (alert in this test). The alert pops up on any pages, regardless if the url contains one of the ids from the array or not. What is wrong with my if statement: if(pageHref.indexOf(id))? thanks for any advise

var pageHref = window.location.href;
var ids = ['14528','14417','17529'];
for (var i = 0; i < ids.length; i++) {
    var id = ids[i];
    if (id.length > 0) {
        if(pageHref.indexOf(id)){
            //do something
            alert('a');
        }
    }
}
6
  • 2
    ids.find(id => pageHref.indexOf(id) !== -1) Commented Jul 28, 2016 at 12:45
  • indexOf return -1 if nothing found Commented Jul 28, 2016 at 12:45
  • Why negative votes for answers? Commented Jul 28, 2016 at 12:52
  • Good question.. very weird ... Commented Jul 28, 2016 at 12:55
  • 1
    thanks, that was very helpful, everyone. I don't yet have reputation of 15, so it won't count my up-votes for you. Why did someone gave the answers negative? they all work Commented Jul 28, 2016 at 13:24

1 Answer 1

-2

IndexOf returns a number, if the number is -1, there is no match.

Try for example. pageHref.indexOf(id) != -1.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.