Reputation: 2415
I have the following function below that's returning an error
j is not defined
I'm not sure why this is as i in my first for loop is not returning undefined. If I change the second forloop to for(var j =0.... then it works. Anyone care to explain why this is?
;(function (window, document, undefined) {
'use strict';
var DOMState = document.readyState;
if (DOMState === 'interactive' || DOMState === 'complete') {
setTimeout(init, 250);
} else if (document.addEventListener) {
document.addEventListener('DOMContentLoaded', init);
}
function init() {
var links = $('#list_of_recs a');
for (i=0;i<links.length;i++) {
var href = links[i].href;
var campaignCode1 = "?intcam=ON_D_homepage_recently_viewed";
var newHref = href + campaignCode1;
links[i].href = newHref;
}
var recTotalDevices = $('#list_of_recs .one_image');
for (j=0;j<recTotalDevices.length;j++) {
var aLinks = $('#list_of_recs a')[j];
var link = aLinks.href;
var newLink = link.replace("upg-","");
var newLinknew = newLink.replace("additional-line","");
aLinks.href = newLinknew;
}
}
})(window, document);
Upvotes: 0
Views: 103
Reputation: 101738
JavaScript strict mode prevents using variables that have not been declared. You have not declared j
so that is why you are getting an error.
As to why you are not getting an error for i
, this is most likely because some other code in your page has declared a global i
variable.
You should be declaring both.
Upvotes: 2
Reputation: 21
Without the full context of any other scripts that are running on your page it's hard to be certain but likely there is another script on your page which contains an global scope assignment to i=0 as it is a common convention.
I would suggest you place a
var i=0,j=0;
at the start of your function to ensure localised variables are being referenced in your loop. This is better practice than putting the var in the top of the for() loop
Upvotes: 0