This is a basic for loop question. If I have a simple for loop such as:
function printMe()
{
for(var i = 0; i < 5; i++)
{
document.getElementById("text").innerHTML = i;
}
};
printMe();
When I call the function, it only prints the last number in the loop 5. But, how can I make it print ever iteration of the loop so the final list is 0, 1, 2, 3, 4, 5
You are constantly overwriting the value of innerHTML because you are using innerHTML = i. This means that when the loop has finished running, the value will be the last value of i.
You want to use += to append i to the existing value, and you might want to add a space after that as well so they aren't glued together.
document.getElementById("text").innerHTML += i + " ";
Which is a shorthand notation for
document.getElementById("text").innerHTML = document.getElementById("text").innerHTML + i + " ";
Thus: get the old value, add the new value, store it once again in innerHTML.
The problem is you are assign i into innerHTML each loop (not append +=), so it is an expected behavior to have the only last output
Try the following will be fine
function printMe()
{
for(var i = 0; i < 5; i++)
{
var innerHTML = document.getElementById("text").innerHTML;
document.getElementById("text").innerHTML += (innerHTML.length <= 0 ? "" : ", ") + i;
}
};
printMe();
and also if you would like to print the 5 also, you have to change the for loop to for (var i = 0; i < 6; i++) or for (var i = 0; i <= 5; i++)
try it on https://jsfiddle.net/v1jnLw23/
Related
I've been trying to figure this out for a while but have run out of possible solutions. This is for a school assignment that is meant to create a "triangle" based on the number inputted (so if I put 3, the first line will have 1 asterisk, the second will have 2, and the third 3). The code is running fine but I'm getting an extra empty line because of the "\n" and am unsure how to remove it. My code:
function drawTriangle(size) {
let string = ""; //declares a variable string
for (let i = 1; i <= size; i++) { //loop continues upto size
for (let j = 0; j < i; j++) { //loop starts from 0 and ends at i
string += "*"; //* is added to string
}
string += "\n"; //when 1 row is finished, next line is printed on new line
}
console.log(string); //outputs the string to the console
}
As per Bergi's comment, create a local array variable and add line break at the end by using .join("/n").
Live Demo :
function drawTriangle(size) {
let str = ''; //declares a variable string
const arr = [];
for (let i = 1; i <= size; i++) { //loop continues upto size
for (let j = 0; j < i; j++) { //loop starts from 0 and ends at i
str += "*"; //* is added to string
}
arr.push(str);
str = '';
}
return arr
};
const result = drawTriangle(3).join("\n");
console.log(result);
I am teaching myself programming and I am doing a Udacity course on Javascript. They have a quiz to create a for loop in a function to create a triangle and call that function in another function. I wrote a for loop (pasted below) that worked in Java but is not working in Javascript. Can you point out my mistake please? The code is only printing 1 "*".
Code I wrote:
function makeLine(length){
var line = "";
for(var i = 1; i <= length; i++){
for(var j = 1; j <= i; j++){
line += "* ";
}
return line + "\n";
}
}
function buildTriangle(input){
makeLine();
}
console.log(buildTriangle(10));
function makeLine(length) {
var line = '';
// outer loop is number of lines
for (var i = 1; i <= length; i++) {
// inner loop is number of stars for this line
for (var j = 1; j <= i; j++) {
line += '* ';
}
// after requisite number of stars, add a new line char to end this line, before returning to the outer loop
line += '\n';
}
// return your finished string to the calling function
return line;
}
function buildTriangle(input) {
// need to send "input" to the makeline function
// since you are not printing here.. you need to return the result of this function
// to the calling function, so console.log has something to print.
return makeLine(input);
}
console.log(buildTriangle(10));
Also, I might use descriptive variable names instead of i, j just to make it easier to read, and to add clarity.
For example:
for (line_num = 1; line_num <= length; line_num++)
and
for (star_num = 1; star_num <= line_num; star_num++)
makeLine dont use return in loop, in buildTriangle call the function makeLine with arg input and return it
function makeLine(length){
var line = "";
for(var i = 1; i <= length; i++){
for(var j = 1; j <= i; j++){
line += "* ";
}
line += "\n";
}
return line;
}
function buildTriangle(input){
return makeLine(input);
}
console.log(buildTriangle(10));
Based on the name makeLine I am rather convinced that you are supposed to make only a single line there, then make a triangle by repeatedly calling from buildTriangle:
function makeLine(length){
var line='';
for(var i=0;i<length;i++)
line+="*";
line+="\n";
return line;
}
function buildTriangle(input){
var tri="";
for(var j=0;j<input;j++)
tri+=makeLine(j+1);
return tri;
}
console.log(buildTriangle(5));
So I have this for loop, I'm stuck in the second one, but If I am, I'd also be stuck in the first one, whats the problem here?
for(var i = 0; i < oldtds.length;i += 3)
{
var oldNameIndex = sameName(oldtds[i].innerHTML, nameList);
if(oldNameIndex != -1)
{
//This means the name already exists
//I need to combine the times, and remove the tr from the table for the second name
//this loop accesses all the times
for(var j = i + 1; j < oldtds.length; j += 3)
{
//This won't quite work, There are colons between them
var timerArray = oldtds[j].innerHTML.split(":");
timerArray.push(oldtds[oldNameIndex + 1].innerHTML.split(":"));
console.log(timerArray);
console.log("this is j " + j);
}
}
}
If I have variables and a for loop with a condition set-up like this:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++)
Does the i refer to the scores array indexed position of 0, or is i just the counter number, which is set to 0?
I'm kinda confused on understanding what's happening.
Any help is appreciated!
Here you can see it in action:
var scores = [23, 53, 85];
var arrayLength = scores.length;
var i;
for(i = 0; i < arrayLength; i++) {
console.log('i = ' + i + ', scores[i] = ' + scores[i]);
}
console.log('End of for loop: i = ' + i);
One important thing to understand is that i will be incremented until the condition i < arrayLength is not met anymore. So it will reach the value 3 but the for loop will end immediately. Therefore, the code inside the loop is not executed for i = 3.
i is just a counter number which is initially set to 0 and increments up to arrayLength (3 in this case)
i just refers to a number that (in this case) counts up from 0 until arrayLength. You have to explicitly access the values in the array at each i by using scores[i], after which you can modify/use the value in any way you see fit.
i is the counter number.
A for loop works like so:
For each value of array length, use i as a counter variable
each time through the loop increment the variable of i when you are done (i++)
you could expand it like so...
for(i = 0; i < arrayLength; i++)
{
console.log('position ' + i + ' is ' + scores[i]);
}//now that I am done, increment i and go through again until i is no longer less than array length
Right so you have the set the i as a variable by initially going
var i;
Within the for statement you have set the i variable to 0.
for(i = 0; i < arrayLength; i++){
}
Then the for statement is saying if i is less than the array length run the for statement. Each time the for statement runs you are adding 1 to i because of i++;
Every time the for statement will check to see if i is less than the arrayLength if it isnt it will exit out of the for.
So for this instance the for each would run 3 times because the array length is 3.
Make sure you have open and closing brackets on the for statement
So your for statement should look like this.
for(i = 0; i < arrayLength; i++){
}
I am currently trying to create a double nested loop that adds a number to itself, given the number of instances you want it to be added by.
So when you input something in the Number, for example "5" and you input "3" for the number of instances, then the following would be printed:
5=5
5+5=10
5+5+5=15
More information on my JsFiddle
<div>
<h2>Loop</h2>
Number
<input type='text' id='tbox'>
<br>
Number of Instances
<input type='text' id='theNumber'>
<button onclick=doubleLoop;>
Add Numbers.
</button>
</div>
<div id="content">
</div>
<script>
function doubleLoop(){
var theText = document.getElementById('tbox').value;
var theNumber = document.getElementById('theNumber').value;
var content = document.getElementById('content');
content.innerHTML = '';
for (var i = 0; i < theNumber; i++) {
content.innerHTML = content.innerHTML + (i + 1) + ')';
//start of the second part of the Double Loop
for (var j = 0; j < (i + 1); j++){
if (i === 0){
content.innerHTML = content.innerHTML + theText + '=' + theText + '<br>';
} else if (i > 0) {
content.innerHTML = content.innerHTML + theText.repeat(j) + '=' + (theText * (i+1));
}
}
}
}
</script>
Here you go
https://jsfiddle.net/mkarajohn/qkn2ef4L/
function createString(number, times) {
/*
* We will create each side of the equation separately and we will concatenate them at the end
*/
var leftSide = '',
rightSide = '',
i;
for (i = 1; i <= times; i++) {
leftSide += number.toString();
if ((times > 1) && (i < times)) {
leftSide += '+';
}
}
rightSide = number * times
return (leftSide + '=' + rightSide);
}
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
output += createString(theText, i);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
If there is something that is not clear feel free to ask.
EDIT: If you are hell bent on doing it with two nested loops, here's how it would go:
function loop(){
// .value returns a string, so we make sure the values are converted to integers by calling parseInt()
// See https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/parseInt
var theText = parseInt(document.getElementById('tbox').value);
var theNumber = parseInt(document.getElementById('theNumber').value);
var content = document.getElementById('content');
var output = '';
var leftSide = '',
rightSide = '';
content.innerHTML = '';
for (var i = 1; i <= theNumber; i++) {
leftSide = '';
for (var j = 1; j <= i; j++) {
leftSide += theText.toString();
if ((i > 1) && (j < i)) {
leftSide += '+';
}
}
rightSide = theText * i;
output += (leftSide + '=' + rightSide);
output += '<br />'
}
content.innerHTML = output;
}
var button = document.getElementById('run');
run.addEventListener('click', loop);
First things first: You're naming your variables very poorly, it's really difficult to understand what you're trying to do, specially when you don't say what you want directly in the question. doubleLoop says how your function works but not what it does. getMultiplicationProcess would have been a better name. Also, you could be passing the values as arguments and just returning the result, it would look A LOT better.
Anyway, I couldn't figure how you were trying to achieve this. I've renamed your variables and did everything my way. Never name a variable theNumber or theText because doing so says nothing about what information it holds. You could have named them firstInput and secondInput but even that way it would not be clear.
Here's the code, scroll down for explanation:
var submit = document.getElementById("submit"),
firstInput = document.getElementById("tbox"),
secondInput = document.getElementById("theNumber"),
answerField = document.getElementById("content");
submit.addEventListener("click", function () {
answerField.innerHTML = getMultiplicationProcess(Number(firstInput.value), Number(secondInput.value), "<br/>");
});
function getMultiplicationProcess(multiplicand, multiplier, lineBreak) {
var result = "";
for (var i = 0; i < multiplier; ++i) {
for (var j = 0; j < i + 1; ++j) {
if (i === j) {
result += multiplicand + " = " + (multiplicand * (i + 1));
} else result += multiplicand + " + ";
}
result += lineBreak || "\n";
}
return result;
}
JSFiddle
Explanation:
The outer for loop runs as many times as the second input, or multiplier. So if you input 5 and 3 respectively this loop will run three times. It represents each line of the resulting string.
The inner loop runs as many times as the current iteration number of the outer loop more one. So for our example inputs it will run like this:
0: 1; 1: 2; 2: 3;
I use it to place the multiplicand multiple times in the current line.
The first line will contain a single 5 (not including the answer for this multiplication) so j is i + 1 which is 1 because during the first iteration from the outer loop i equals 0:
5 = 5
The second line contains 2 5s and i is 1 because we're in the second iteration for the outer loop, so j = i + 1 = 2 which is how many fives we'll place in the string:
5 + 5 = 10
if it's the last iteration of the inner loop instead of adding "5 + " to the resulting string it places "5 = (i + 1) * multiplier" which will be the result for the current line. Then the inner loop ends, the outer loop adds a line break and restarts the process for the next line.