My journey doesn't begin at zero

This piece of code triggers an alert message saying 'test 1', followed by an alert indicating the number 8!

uri = 'http://www.scriptcopy.com/';
compareuris = new Array();
compareuris[0] = 'http://www.scriptcopy.com/';
compareuris[1] = 'https://www.scriptcopy.com/';
compareuris[2] = 'http://www.www.scriptcopy.com/';
compareuris[3] = 'https://www.www.scriptcopy.com/';
compareuris[4] = 'http://scriptcopy.com/';
compareuris[5] = 'https://scriptcopy.com/';
compareuris[6] = 'http://www.scriptcopy.com/';
compareuris[7] = 'https://www.scriptcopy.com/';
searchuri = 'http://www.google.com/search?';
searchuri += 'q='+ encodeURIComponent(uri) +'&btnG=Search+Directory&hl=en&cat=gwd%2FTop';
req = new XMLHttpRequest();
req.open('GET', searchuri, true);
req.onreadystatechange = function (aEvt) {
    if (req.readyState == 4) {
        if(req.status == 200) {
            searchcontents = req.responseText;
            parsedHTML = sc_HTMLParser(searchcontents);
            sitefound = sc_sitefound(compareuris, parsedHTML);
        }
    }
}
req.send(null);
function sc_HTMLParser(aHTMLString){
   var parseDOM = content.document.createElement('div');
   parseDOM.appendChild(Components.classes['@mozilla.org/feed-unescapehtml;1']
      .getService(Components.interfaces.nsIScriptableUnescapeHTML)
      .parseFragment(aHTMLString, false, null, parseDOM));
   return parseDOM;
}
function sc_sitefound(compareuris, parsedHTML) {
    gclasses = parsedHTML.getElementsByClassName('g');
    alert('test 1');
    for (i = 0; i < gclasses.length; i++) {
        alert(i);
        gclass = gclasses[i];
        atags = gclass.getElementsByTagName('a');
        tag1 = atags[0];
        hrefattribute1 =  tag1.getAttribute('href');
        uri1 = hrefattribute1;
        compareduris = sc_compareuris(uri1, compareuris);
        alert('test 2');
        if (compareduris) {
            sitefound = uri1;
            return sitefound;
            alert('test 3');
        }
        alert('test 4');
    }
    return null;
}
function sc_compareuris(uri, compareuris) {
    for (i = 0; i < compareuris.length; i++) {
        compareuri = compareuris[i];
        if (uri == compareuri) {
            return true;
        }
    }
    return false;
}

Highlighted section:

    alert('test 1');
    for (i = 0; i < gclasses.length; i++) {
        alert(i);

What is the reason for this behavior and how can it be fixed?

Answer №1

I've encountered issues similar to this in Internet Explorer previously. To ensure that i is locally scoped, it's recommended to always use the var keyword within a for loop:

alert('test 1'); 
for (var i = 0; i < gclasses.length; i++) { 
    alert(i);
    // etc...
}

Alternatively, you can declare the variable within the same scope before using it:

var i;
alert('test 1'); 
for (i = 0; i < gclasses.length; i++) { 
    alert(i);
    // etc...
}

For more information, you can refer to:

Variable scope in JavaScript for loop
http://developer.mozilla.org/En/Core_JavaScript_1.5_Reference/Statements/Var

Answer №2

Are there any additional alerts that haven't been included in the code snippet? What if you modify it to:

alert('test 1, gclasses.length = '+gclasses.length);
for (var i = 0; i < gclasses.length; i++) {
    alert(i);

I'm curious if that loop is actually running?

Answer №3

It is recommended to declare variables locally within each function where they are used, rather than assigning them globally. By keeping variables local, you reduce the risk of unintentional changes from other concurrently running functions. This practice ensures greater control and predictability in your code.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Warning: Attempting to destructure the property 'name' from 'req.body', which is undefined, is causing a TypeError

Currently, I am diving into the world of MERN Stack web development and running into a unique issue. When using Postmate to input data from the body to the database, everything works smoothly when done from the server.js file. However, when attempting the ...

Google Cloud Platform (GCP) reported a Stripe webhook error stating that no matching signatures were found for the expected signature

Current Stripe version: "8.107.0" I am encountering an issue with Stripe webhook verification whenever I deploy my webhook on Google Cloud Platform (GCP). Despite trying various methods to include the raw body in the signature, including the cod ...

What is the best way to extract just the hours and minutes from a timestamp column that includes hours, minutes, and seconds in my dataset and create a new column

Is there a way to extract only the hour and minute values from a timestamp column that includes seconds in my dataset? ...

What is the best way to determine the accurate size of a div's content?

There are 2 blocks, and the first one has a click handler that assigns the block's scrollWidth to its width property. There is no padding or borders, but when the property is assigned, one word wraps to the next line. The issue seems to be that scrol ...

The AJAX .load() function will fail to retrieve any content

Currently delving into the world of JQuery/AJAX and experimenting with a simple 'load' function. Strangely, when I trigger the function on an element within my HTML code, it appears unresponsive. No error messages are being generated, leaving me ...

Unable to access Bootstrap dropdown menu after initial ajax form submission

I am encountering an issue with a dropdown menu on my webpage, specifically within the manager.php file. Please excuse any formatting discrepancies as I am using Bootstrap: <!-- Bootstrap --> <script type="text/javascript" src="https://netdna ...

Angular JS: Saving information with a promise

One dilemma I am facing is figuring out where to store data that needs to be accessed in the final callbacks for an http request. In jQuery, I could easily handle this by doing the following: var token = $.get('/some-url', {}, someCallback); tok ...

Injecting services differently in specific scenarios in AngularJS

I have a unique angular service called $superService that I utilize across many of my directives and controllers. However, there is one specific directive where I want to implement the following behavior: If another directive utilizes $superService in its ...

Converting JSON data retrieved from a URL into HTML format

I have a JSON output from a URL that I need to format into html. The structure of the JSON data is as follows: prtg-version "xxxxxxx" treesize 0 channels 0 name "Downtime" name_raw "Downtime" lastvalue "" lastvalue_raw "" 1 name ...

Ways to sort through a Unix timestamp

Recently, I encountered an issue with my Ionic mobile application. It has a search button and filter feature that works well for filtering words. However, the problem arises when it comes to filtering dates displayed in the app as timestamps using Angular ...

What could be the reason for the inability to install Angular JS 2?

Setting up Angular 2 for experimentation on my VPS has been quite a challenge. The initial steps can be found here. Upon trying the first command: $ npm install -g tsd@^0.6.0 I encountered success. However, the second step led to an error: tsd install ...

Sorting and Uploading Images made Easy with Drag-and-Drop Functionality

Currently, I am developing a webpage and exploring the option of implementing a drag-and-drop image upload system that allows users to remove and sort images before uploading. I am seeking your opinion on this matter. I am concerned about potential issue ...

How can I implement API redirection in my Node.js application?

Currently, I am working on a mock authentication system in Node.js using passport and JWT. I have successfully created an API and I am using handlebars for templating. My dilemma arises when a user tries to login by sending their credentials to the API. I ...

Executing a task within a Grunt operation

I have integrated Grunt (a task-based command line build tool for JavaScript projects) into my project. One of the tasks I've created is a custom tag, and I am curious if it is feasible to execute a command within this tag. Specifically, I am working ...

Using the video-js feature to play multiple videos simultaneously

Is it possible to play multiple videos using video-js functionality simultaneously? The answer is yes! Check out Fiddle 1 However, an issue arises when wrapping a trigger, such as a button, around the function that invokes playVideo(). This causes the v ...

Notify other viewers that a button has been activated

I'm working with a basic HTML file that contains two buttons. When one of these buttons is pressed, I want to notify another user in some way within a few seconds. <html> <body> <input type="button" value="Button 1"& ...

unable to retrieve value from JSON object

It appears that I'm having trouble accessing my object variables, most likely due to a silly mistake on my part. When I console.log my array of objects (pResult), they all look very similar with the first object expanded: [Object, Object, Object, Obj ...

Is there a way for me to detect when the progress bar finishes and execute a different function afterwards?

After clicking a button in my Javascript function, the button disappears and a progress bar is revealed. How do I trigger another function after a certain amount of time has passed? $('#go').click(function() { console.log("moveProgressBar"); ...

Building queries on the client side with Django

For my AJAX-driven web page that relies on JSON responses from API queries, I am facing the issue of constantly needing to update the API interface whenever new functionalities are required. These updates typically involve crafting database queries and con ...

Navigating the route on express.js using two strings can be done by matching them effectively

I have a single route function that should match two different paths. The goal is to create profile pages for team members on a website, which can be accessed at www.domain.com/name. However, some team members prefer to use nicknames instead of their actua ...