I'm seeking assistance in grasping the reasoning behind this particular 'for loop'

Currently engaged in learning on Code Academy, where I am enjoying the process. The topics of push and nested for loops were introduced rather quickly without much initial information. My grasp on the logic is somewhat there, but I would appreciate some help breaking it down...

var text = "Here is a string with the name rick sometimes not always rick   and sometimes rick";
//assigning the text string to the variable 'text'

var myName = "rick";  
//assigning 'rick' to the variable 'myName'  
var hits = [];  
//assigning an empty array to store hits
for (var i = 0; i < text.length; i++); {  
    //for loop starting from zero and incrementing as long as i is less than the length of the entire text string

    if (text[i] === "r") {  
        //if the character at index i is 'r', enter the second for loop  

        for(var j = i; j < (i + myName.length); j++){  
            //setting up another for loop starting from i and running for the length of myName which is 4 characters

            hits.push(text[j]);  
            //adding each letter of my name to the hits array 
        }  
    }  
}  

My code is currently not working. Upon adding a console.log statement under the first for loop, it simply prints 84. "console.log("I= " +I)" I realize this may be basic, but I am eager to comprehend the logic behind it. Am I on the right track?

Answer №1

You're on the right track!

Just one little issue:

  • The ";" after the for loop is unnecessary and serves no purpose.

Remove it, and everything should work smoothly!!

Another tip you might find useful is to add all words following the 'r' character to the list "hits."

Here's what you should do:

if (text[i] === "r") {  
    var word = "";
    for(var j = i; j < (i + myName.length); j++) {  
        word += text[j];
    }  
    hits.push(word);  
}  

Also, ensure that i + myName.length remains within the bounds of text.length (i + myName.length < text.length)

Hope this information proves helpful!

Answer №2

Your code is almost there, but there's a small mistake. You mistakenly added a semicolon after your first for loop:

for (var i = 0; i < text.length; i++);

This basically turns it into a one-line block, similar to this:

for (var i = 0; i < text.length; i++) {
}

Remove that semicolon and the code should work as intended : ). If you only want to push "rick" in, make sure to check for more than just the letter "r". Validate that each character following is also equal to "rick".

Answer №3

A semicolon is incorrectly placed after the 'for' statement in your code. Additionally, the length of your string still limits the loop. Therefore, your corrected for statement should look like this:

for(var j = i; j < (i + myName.length) && i < text.length; j++){  

For instance, if your string has a length of 82 characters and you find an 'r' at index 81 (i = 81), your original loop would attempt to check beyond the actual length of the string, causing an error. By adding the extra condition i < text.length, you ensure that you don't go out of bounds.

If you're new to programming, it's worth mentioning that '&&' represents logical AND, meaning j must be within the specified ranges to execute properly.

Check out this working example on JSFiddle (http://jsfiddle.net/onlinespaces/xj39974c/1/)

JSFiddle can be a valuable resource for debugging and testing code like this.

Best of luck with your coding!

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

Toggle Jquery menu with a click of a button

I need help with creating a menu for a forum that opens on click and closes on click. Here is the code I have so far: /*Custom BBPress admin links menu*/ function wpmudev_bbp_admin_links_in_menu($retval, $r, $args) { if ( is_user_logged_in() ) { $me ...

Manipulating the DOM with Javascript and jQuery: Adding a new element and retrieving its reference

I am encountering an issue with a Web App that relies on JavaScript and jQuery. Essentially, the website includes a button that triggers a JavaScript function when clicked. Within this function, there are two other functions named Foo and Bar. Foo generate ...

Strategies for aligning tooltips with the locations of dragged elements

One of my projects involves a simple drag element example inspired by Angular documentation. The example features a button that can be dragged around within a container and comes with a tooltip. <div class="example-boundary"> <div ...

Using jQuery to extract the value from a string using logical operations

One challenge I am facing involves manipulating a string stored in a jQuery variable (var str). The string looks like this: var str = 4-68,4-69,4-70,5-86,5-87,5-88,5-89,5-91,6-100,6-101 My goal is to organize the string and transform it into the followin ...

Unique Symbols and Characters in JavaScript

My JavaScript code looks like this: confirm("You are selecting to start an Associate who is Pending Red (P RD) status. Is this your intent?") I am encountering a strange issue where I get an alert with special characters, even though my code does not con ...

A guide on updating URLs that are not enclosed within an anchor tag using JavaScript

In my current scenario, I am dealing with text that includes URL links presented in two different formats. www.stackoverflow.com <a href="http://www.stackoverflow.com">Stack over flow</a> My objective is to create a straightforward function ...

In TypeScript, the Select element does not contain an options property

Having trouble iterating through a TypeScript array. Here are the methods I'm using: getNotification(evt: string, rowIndex: number) { console.log("Production order: law has changed to " + evt + " " + rowIndex); var select = document.getEleme ...

Using Cordova plugman to add the initial platform-specific plugin into the project

Here are the system dependencies: cordova: @7.1.0 plugman: @2.0.0 I am trying to use plugman specifically for installing plugins on a particular platform (such as android). Having reviewed the documentation, I find that the workflow and usage is not en ...

Filter error - Unable to retrieve property 'toLowerCase' from null value

When filtering the input against the cached query result, I convert both the user input value and database values to lowercase for comparison. result = this.cachedResults.filter(f => f.prj.toLowerCase().indexOf((this.sV).toLowerCase()) !== -1); This ...

In PHP, you can use the `echo` statement to output an HTML input

Incorporating HTML into PHP using heredoc methodology can sometimes lead to challenges when trying to retrieve user input variables. Attempting to access the input variable with $_GET["input"] may result in an error message indicating an undefined index: ...

Steps for resolving the "endless redirection loop" issue in Sharepoint

I am currently learning Javascript and working on setting up a multi-language Sharepoint site. I am trying to implement a code into each page that checks the user's email and the language in the URL (Portuguese or Spanish) and then redirects according ...

What could be the reason for the 'if' statement not being assessed in the 'then' promise of the ajax request?

I'm facing an issue with an ajax call in my code. I have a 'then' promise set up to handle errors, where the console log returns false correctly when there is an error. However, for some reason, the if condition in the next line is not being ...

Sorting the lines of a file using Bubble sort in Java

Can anyone help me with bubbling sorting a text file containing game release dates? Here is an example of the content: 04/26/16 Sega 3D Classics Collection 07/14/16 Batman: Arkham Underworld 06/24/16 Tokyo Mirage Sessions #FE I want to sort them in th ...

Convert JSON information for use in ChartJS

I've been delving into the world of ChartJs and have encountered a bit of a roadblock. I'm looking to decipher how to convert JSON data into labels and data for a bar chart. The JSON data consists of an array of product orders. With varying numb ...

changing pictures with jquery

Struggling with this code snippet: $('#clicked_package').css({"background-image" : "url(img/head_2.png)"}).fadeOut("slow"); $('#clicked_package').css({"background-image" : "url(img/head_2_normal.png)"}).fadeIn("slow"); No matter which ...

Executing python code from a JavaScript (Node.js) program without the need to create a child process

I have a unique setup where my hardware is running on nodejs, while my machine learning code is written in python3. My goal is to invoke the python3 program from nodejs (javascript) and pass data as arguments to the Python script. While researching, I cam ...

Encountering abnormal behavior when working with a pointer to an array

Take a look at the code snippet provided: #include<stdio.h> int main() { int (*p)[3]; int a[3]={10,11,12}; p=&a; printf("%d\n", *p[0]); printf("%d\n", *p[1]); printf("%d\n", *p[2]); return 0; } ...

Stop automatic page refresh after submitting a jQuery post request

I've tried various solutions, but unfortunately, neither e.preventDefault() nor return false seem to be working for me. When I use prevent default ajax doesn't make post request. Even using $.post doesn't work as expected. Furthermore, addin ...

issues with the handler not functioning properly in html and javascript

<form method="post" action="."> <label class="input-label">Enter Your First Name</label><input field="first_name" class="input-edit" maxlength="30" type="text" value="{{ user.first_name }}" /> <label class="i ...

Refresh the current AngularJS page while preserving the stateParams

I am currently working on a function that toggles the display of a button based on data retrieved from an external API. When loading a record, I pass in an 'id' parameter ($stateParams.id) If the value of this parameter is 1, a button will be s ...