What does this code means? (Javascript FOR loop) [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 7 years ago.
Improve this question
Can someone explain this code to me?
Any help will be appreciated ! Thanks!!
<p id="arrayString"></p>
<script type="text/javascript">
var arrayString = "";
var myArray = ["pizza", "hamburger", "chicken leg"];
for (var i = 0; i < myArray.length; i++){
arrayString = arrayString + myArray[i] + " ";
}
document.getElementById("arrayString").innerHTML = arrayString;
</script>
</body>

Here is the code with some comment:
<p id="arrayString"></p>
<script type="text/javascript">
var arrayString = ""; //store an empty string in the variable (the purpose is to initialize the variable in wich after(for loop) we will store the names)
var myArray = ["pizza", "hamburger", "chicken leg"]; //create an array with some string elements
//foreach element in the array (the strings)...
for (var i = 0; i < myArray.length; i++){
//...add the 'i-est' element of the array to the string variable 'arrayString' and insert a space after the element
arrayString = arrayString + myArray[i] + " ";
}
//print the string in the html element with id 'arrayString'
document.getElementById("arrayString").innerHTML = arrayString;
</script>
</body>
The for statement iterates over the elements of the array, and in each iteration you access an element with: myArray[i]
Check here to see how the for loop works

I'm assuming you mean the for loop and not the other stuff.
for loops are basically while except more organized. for(var i = 0; is making the variable that is going to determine when to end the for loop.
i < myArray.length; is basically while(i < myArray.length) aka while i is less than myArray length it will do what's inside.
lastly, i++; tells the for loop what to do to i at the end of the statement to eventually make it >= to myArray.length.

The for loop creates a variable i and executes the code within the loop as long as i is less than the length of myArray. Each time the code in the loop is executed, i is increased by 1.
for (var i = 0; i < myArray.length; i++) {
arrayString = arrayString + myArray[i] + " ";
}
is saying for the variable i, if i < myArray.length, execute the code arrayString = arrayString + myArray[i] + " "; which adds the ith element of myArray to arrayString. For example, when the loop starts, i=0. So if it is true that i < myArray.length, then the 0th, or first, element of myArray is added to arrayString (Since array indexing begins at 0: 0 is the first element, 1 is the second, 2 is third, and so on. Then, once that is finished, the flow of control jumps back into the conditions in the for loop and executes i++, or "increase i by one". This whole process continues until the statement i < myArray.length is false (meaning i >= myArray.length, in which case the code in the for loop will be trying to add elements of the array that do not exist, like "add the 6th element of a 5 item long list").
The last line,
document.getElementById("arrayString").innerHTML = arrayString;
gets the element in the document with the id "arrayString" and displays the text contained in arrayString in that element (which is the one defined at the top in paragraph tags).

It's converting an array into a string. You could just use this, though:
document.getElementById("arrayString").innerHTML = myArray.join(' ');

Related

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] + ".");
}

Javascript: attempting to fill an array with a prompt but prompt is not displaying

I am attempting to call a method that asks the user how many entries they would like to make into an array and then prompts the user for each entry. I know this is likely a simple error but I cannot tell why my prompt is not working.
<script>
function testScore(){
var numberofScores = prompt("enter the number of scores:","");
var scores = new Array();
var whichScore=1;
for(var i=0; i<numberofScores; i++; whichScore++){
score[i]=prompt("enter score "+whichScore+":");
}
}
</script>
<a href="" onclick="testScore()">
Start Test score script
</a><br>
A loop is configured with 3 sections and thus two semi-colons. You had whichScore++ in a 4th section after adding a third semi-colon. You could have added it to the end of the configuration with a comma. But, adding it to the loop body, and not part of the loop declaration is cleaner. That said, the variable is not even needed. Just use (i + 1) and note that we're not modifying i here, we're just using an offset of it for display purposes only.
Also, in the loop: score[i], needs to be scores[i] and your <a> element should have an href="#" instead of an empty attribute.
Lastly, don't use inline HTML event handling attributes as they:
Make the code more difficult to read and lead to code duplication.
Cause global wrapper functions to be created around your supplied
attribute value that alter the binding of this in your function.
Don't follow the W3C DOM Event standard.
Use .addEventListener() in JavaScript instead:
// When the DOM content is ready
window.addEventListener("DOMContentLoaded", function(){
// Get a reference to the hyperlink and create a click event handler for it:
document.getElementById("makeScores").addEventListener("click", testScore);
function testScore(){
var numberofScores = prompt("enter the number of scores:","");
var scores = new Array();
for(var i = 0; i < numberofScores; i++){
scores[i] = prompt("enter score " + (i + 1) + ":");
}
console.log(scores);
}
});
Start Test score script
Here is a JSFiddle using your code. You have a lot going on here
https://jsfiddle.net/tcoedqkf/
First off, your for loop needs to have a comma besides the increments (although for readability I would do it in the for loop)
for(var i=0; i<numberofScores; i++,whichScore++){
Your variable name in the for loop is incorrect (missing an S)
scores[i]=prompt("enter score "+whichScore+":");
<script>
function testScore(){
var numberofScores = prompt("enter the number of scores:","");
var scores = new Array();
var whichScore=1;
for(var i=0; i<numberofScores; i++, whichScore++){
scores.push(prompt("enter score "+whichScore+":"));
//or
//scores[i]= (prompt("enter score "+whichScore+":"));
}
}
</script>
<a href="" onclick="testScore()">
Start Test score script
</a><br>
your variable is scores
Use Array.push, since you did not declare the array length in array constructor. Edit : You can also use scores[i]. It will work as well.
for only have three sections (separated by a semicolon ;): initialization, the condition and the incrementation. If you want to initialize or increment more variables use a comma ,. Like this:
for(var i = 0; i < numberofScores; i++, whichScore++) {
// ...
Since whichScore is basically just i + 1 you won't need to have two variables for that, just i will do:
for(var i = 0; i < numberofScores; i++) {
score[i] = prompt("enter score " + (i + 1) + ":");
// ...
Note that the parenthesis in (i + 1) are necessary so the numbers are added instead of concatenated.

Javascript stuck at "for" loop

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.

Re-initializing Javascript array inside loop re-initializes it each time through the loop

I wrote this code to create an array but if I check array at the iteration ending only contains the last element created. It should have 7 elements because the iteration happened 7 times.
for (i = 0; i < intersects[0].object.geometry.vertices.length; i++) {
console.log(i);// print 7 times
var dist=euclideanDistance(intersects[0].object.geometry.vertices[i], intersects[0].point);
map = {v:intersects[0].object.geometry.vertices[i], d:dist};
var array=[];
array.push(map);
}
console.log(array); //only contains one last element
Put the var array=[]; before the loop. As it stands, it's overwriting array with a new instance at each pass.
// declaration should go above loop. lateralus has suggested in comment
var array=[];
for (i = 0; i < intersects[0].object.geometry.vertices.length; i++) {
console.log(i);// print 7 times
var dist=euclideanDistance(intersects[0].object.geometry.vertices[i], intersects[0].point);
map = {v:intersects[0].object.geometry.vertices[i], d:dist};
array.push(map);
}
console.log(array); //only contains one last element

Categories