Javascript stuck at "for" loop - javascript

i am newbie learner and i am learning basic javaScript from codecademy.I stuck at "Search Text for Your Name" tutorial 5/7.
here is my question:
your loop should stop when it hits the value of the first iterator (say, i)
plus the length of your myName variable.
here is some informations from to tutorial:
Your second "for" loop
Okay! Last loopy step: add another for loop, this time inside the body of your if statement (between the if's {}s).
This loop will make sure each character of your name gets pushed to the final array. The if statement says: "If we find the first letter of the name, start the second for loop!" This loop says: "I'm going to add characters to the array until I hit the length of the user's name." So if your name is 11 letters long, your loop should add 11 characters to hits if it ever sees the first letter of myName in text.
For your second for loop, keep the following in mind:
First, you'll want to set your second loop's iterator to start at the first one, so it picks up where that one left off. If your first loop starts with
> for(var i = 0; // rest of loop setup
your second should be something like
> for(var j = i; // rest of loop setup Second
think hard about when your loop should stop.
Finally, in the body of your loop, have your program use the .push() method of hits. Just like strings and arrays have a .length method, arrays have a .push() method that adds the thing between parentheses to the end of the array. For example,
newArray = [];
newArray.push('hello');
newArray[0]; // equals 'hello'
and here is my code:
multistr:true
var text = "Hey, how are you \
doing? My name is Emily.";
var myName = "Emily";
var hits = [];
for (var i = 0; i > text.length; i++)
{
if (text[i] === 'E')
{
for(var j = i; j > text.length; j++){
};
};
};
ps: i don't want to pass this tutorial without understand it. please help me. teach me.

for (var i = 0; i > text.length; i++) should be
for (var i = 0; i < text.length; i++)
otherwise it won't ever meet the criteria to even start the loop.

Welcome on board! You confused > with <. Your loops won't run because for the first check when i = 0 it certainly does not hold that 0 > text.length, because text.length is at least 0 (there are no strings shorter than the empty string).
You should make a habit of manually going through your loops for the first two steps and then check what happens just before the loop ends.

Here is what I got for my code:
for ( i = 0; i < text.length; i++)
{
if ( text[i] === "E")
{
for( var j = i; j < (myName.length + i ); j++)
{
hits.push(text[j]);
}
}
};
It looks like you were missing the " + i " part in your second for loop. That seems to make sure that the first loop will be included. I tried it without the "+ i" and it does not work.
I tried continuing directly from the second for loop using a "+ j" and that only crashes the browser.

Related

Infinite Loop for finding a power set for a string

I'm working on a problem where I need to find all the power set of a given string which are all the possible subsets. I feel like I'm close with my current code but I can't figure out why I'm getting stuck on an infinite loop for my second iteration. I ran it through the debugger but I still can't seem to figure it out even though I'm sure it's very simple. When i = 0 then it goes to the second loop where j = 0 && j < 1 so for example if help is my given str argument then I would expect it to add j + '' and push it into my allSubsets array. The problem is that the j iteration will keep looping and doing j++ and will never stop. I'm not sure why this is. One particular question even if I solve this infinite loop - do I need to update the allSubsets.length in the iteration to keep it updated with the pushed in strings?
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
debugger;
for (let j = 0; j < allSubsets.length; j++) {
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
}
}
return allSubsets;
};
var sortLetters = (word => {
//convert string to an array
//use the sort to sort by letter
//convert array back to string and return
return word.split('').sort().join('');
})
Everytime you push to allSubSets, the length increases, and thus, your loop never ends. A declarative loop runs on the range of the initial loop. See below for a fix based on your code:
var powerSet = function(str) {
let allSubsets = [''];
for (let i = 0; i < str.length; i++) {
allSubsets.forEach( (_char, j) => { // declarative loop here
allSubsets.push(sortLetters(str[i] + allSubsets[j]));
})
}
return allSubsets;
};
var sortLetters = (word => {
return word.split('').sort().join('');
})
From MDN web docs:
The range of elements processed by forEach() is set before the first invocation of callback. Elements which are appended to the array after the call to forEach() begins will not be visited by callback. If existing elements of the array are changed or deleted, their value as passed to callback will be the value at the time forEach() visits them; elements that are deleted before being visited are not visited. If elements that are already visited are removed (e.g. using shift()) during the iteration, later elements will be skipped. (See this example, below.)
See the fourth paragraph under descriptions: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#Description

Index does not exist JavaScript?

integrityCheck = function () {
var check = ['098f6bcd', '4621d373', 'cade4e83', '2627b4f6'];
for (var i = 0; i <= check.length; i++) {
checkIntegrityOfData(
i,
check[i]
);
}
}
There is probably a very obvious error in my part of the code but im new at JavaScript so i cant really see it.
Array index starts from 0, meaning if an array has 5 elements, the length would be 5 but the max index would be 4.
With your condition logic
You will need to fix your condition logic i <= check.length, last iteration of the loop will try to access check[4] but the last element in check will be in check[3].
Change your loop condition code to
for (var i = 0; i < check.length; i++) {
The problem is your loop goes up to and including the length of the array, however array length starts from 1 whereas array indexes start from 0. Change it to this:
for (var i = 0; i < check.length; i++) {
And it will work. (All I did was change the i<=check.length to i<check.length so it won't iterate over the last index, which is the thing making the error.

looping through html and deleting not found

So, i'm looping through the document body searching for all "#result>tbody>tr" objects. I'm then trying to search within those elements to see if any of the names exist, if they do, I would like to delete them. I got it working if I don't loop through the names and use a single object. If I try and loop through the names, it only loops four times and then nothing else happens.
Any ideas?
Edit: Currently there are 30 objects the first loop loops through. When I add the second loop into the mix to see if the sub-objects exist, it will only loop through four and than break the loop. Hope that explains better.
Example: https://jsfiddle.net/8c9p7bp5/1/
var dlList = document.querySelectorAll("#result>tbody>tr");
for (var i = 0, len = dlList.length; i < len; i++) {
var names = ['Test', 'Router', 'IP', 'Mod'];
for (var j = 0, len = names.length; j < len; j++) {
var vi = dlList[i].querySelector("td>br>img[title^='" + names[i] + "']");
if(!dlList[i].contains(vi)) {
//dlList[i].remove();
console.log(dlList[i]);
}
}
}
First mistake of your code that you are using same limit for you nested loop "len", in the first iteration the value becomes 4 that's why it will break the parent loop.
You initialize j but never use it in the inner loop.
Try this instead:
var vi = dlList[i].querySelector("td>br>img[title^='" + names[j] + "']");
Also, you should use a different variable than len for the inner loop to avoid running into variable scope issues.

javascript what is wrong with this "for" loop syntax?

Can someone please help me?
I am currently learning Javascript, and I don't understand what's wrong with the following piece of code:
var names = ["vasco", "joão", "francisco", "rita", "manuel"];
for (var i = 0; i < 4; i++); {
console.log("I know someone called " + names[i] + ".");
}
Arrays in JavaScript are zero-indexed. That means the element in the very first position is at index 0. To target that element, you can refer to it like names[0]. In your loop, you are iterating while i < 4, meaning once i becomes 4, the loop stops and does not continue. So you are only calling console.log 4 times. A common practice when iterating through an array is to say i < names.length. Also there are a couple syntax errors as others have pointed out. Below is a working version.
for (var i=0; i < names.length; i++) {
console.log ("I know someone called"+" "+names[i]+".");
}
because you terminate the for loop by semicolon(;) ,so for loop is seperated by its block .
then,
Ques1. what'll do next when code is run?
Ans. when execution comes to for loop, loop executes untill the value of i goes to 4 . then , the next block statement is executed.
Ques2. Why "manuel" is print in o/p?
Ans. answer is simple ,because foor loop terminates when value of i goes to 4 , so
console.log("I know someone called " + names[i] + "."); //it prints the arr[4]
You have ; at the end of your for, just remove it
Please remove the semicolon after the for to be:
var names=["vasco","joão","francisco","rita","manuel"];
for ( var i=0; i <5 ; i ++) {
console.log ("I know someone called"+" "+names[i]+".");
}
also the condition i<4 is the stopping the last case
there are two issues with the code you wrote ,
1- you have a semi-colon after the condition for(condition);
which result in the loop not doing anything
2- you are off by one, last element of the array has index 4
condition should be (i <= 4) or (i < array.length)
var names = ["vasco", "joão", "francisco", "rita", "manuel"];
for (var i = 0; i < names.length; i++){
console.log("I know someone called " + names[i] + ".");
}

How to create and display result one at a time in an infinite loop in javascript?

I'm fairly new to HTML and Javascript. I want to know how to create an infinite loop from, let's say, myArray, list, or whatever and then display result one at a time. Can you please give me an example, hints, or anything with detailed explanation of how it works? I just want to understand on how things work. Thanks!
A very basic loop is a while loop:
while (condition) {
//code block to be executed
}
Typically you would use it like so:
var i = 0;
while (i < 10) {
//code block to be executed
i++;
//This block of code will continue until i >= 10
//adding 1 to the value of I each iteration
}
Easiest way to do a endless loop:
while (true) {
code block to be executed
}
//true will always be true so this will continue until it
//hits a return; statement, the end of time, or the software
//or hardware gives up
A common mistake that end up in an endless loop:
var i = 0;
while (i < 10) {
code block to be executed
//In this example i is never being increased so
//i will always be less than 10
}
A very practical way to do a while loop correctly:
var array = ['a','b','c'];
var i = 0;
while (i < array.length) {
alert(array[i]);
i++;
}
//This will alert a, alert b, then alert c
Another way to do the above is using a for loop:
var array = ['a','b','c'];
for (var i = 0; i < array.length; i++) {
alert(array[i];
}
//for loops are a good practice because you are less
//likely to leave out steps like defining the iterator,
//or increasing the iterator
OP
I'm trying to create something using HTML/Javascript that everytime I press a button called next item (I created one using <form></form>) it would display an item, or an image. The trick is I don't know how to keep displaying the item after the last position. After the last position it should go back to the first position. For example, for the array that you provide in your example you have [a, b, c], after I displayed c and press the button again I want to display a again and so forth. Can you give me hints or any other valuable info on how to do this?
Answer
JSFiddle Example:
http://jsfiddle.net/d2809p6z/
HTML
<button id="button">click me</div>
JS
var array = ['a','b','c'];
var index = 0;
document.getElementById('button').onclick=function(){
if (index >= array.length) {
index = 0;
}
alert(array[index]);
index++;
};

Categories