What's wrong with this code? (Loop through array)

var url = window.location.pathname;  
  
var myPageName = url.substring(url.lastIndexOf('/') + 1);

//pages that shouldn't have the prototype.js script
var excludedPages = new Array(
"admin.php",
"upload.php",
"catmgr.php",
"albmgr.php",
"picmgr.php",
"searchnew.php",
"util.php",
"pluginmgr.php",
"banning.php",
);

for ( var i=0, i<excludedPages.length; ++i ){
	if (myPageName != excludedPages[i]) {
		document.write('<scr'+'ipt type="text/javascript" src="js/prototype/prototype.js"></scr'+'ipt>');
	}
}

What I am trying to do is not get the prototype.js included on those specific pages, as it messes with the forms. However, for all other pages, the prototype.js is fine to be included.

I have tried an if statement like this:

if (myPageName != "admin.php") || (myPageName != "upload.php") {
...
}

But whenever I add a 3rd item, it stops working. I would prefer to have an array as it makes sense and is easy to read, but I can’t figure out what’s going on.

What am I missing?

The trouble with your attempted ‘if’ statement is “short circuit logic”. As soon as a decision can be made (true or false, evaluating from left to right) that answer is returned.

With your loop BEWARE that excludedPages.length will be the EXACT LENGTH of the array. If you loop through the array beginning with zero (which is necessary to access the very first element) your loop will overrun. It will try to continue until “i” equals one more than the index of the last item.
The generally accepted syntax is this:


for ( var i=0, i<excludedPages.length -1; ++i ){

However, if you don’t need to iterate the array in sequence, I prefer a shortcut (according to some things I have read this is also slightly faster)


var i = excludedPages.length;
while (i--) {
//  .... do stuff
}

Because Javascript will evaluate ZERO as a false, this works well.

That code would only ever be true if maPageName were set to both admin.php and upload.php at the same time - which can never happen. To get the resulot you want you need && between the conditions and not ||