-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');
        }
    }
}
  • 2
    `ids.find(id => pageHref.indexOf(id) !== -1)` – gcampbell Jul 28 '16 at 12:45
  • `indexOf` return `-1` if nothing found – Arnial Jul 28 '16 at 12:45
  • Why negative votes for answers? – ssilas777 Jul 28 '16 at 12:52
  • Good question.. very weird ... – KCarnaille Jul 28 '16 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 – GeneticallyModified Jul 28 '16 at 13:24
  • probably because you are not supposed to answer obvious duplicates, it just clutters up the site and dilutes what the `rep` score is supposed to represent. your are supposed to mark them as the duplicate that they are. and you are not going to get rep yourself asking duplicates and other poorly received questions that draw down votes. –  Jul 28 '16 at 20:50

2 Answers2

-1

A blog post here has a table that explains what values evaluate as true in javascript conditional statements. For numerical values it states only +0,-0 and NaN evaluate to false. Because indexOf returns -1 for no match, it is evaluating to true for non-matching ids. You would want to use:

if(pageHref.indexOf(id) > -1)
user3357118
  • 844
  • 7
  • 14
-2

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

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

KCarnaille
  • 1,027
  • 9
  • 18