A pretty dumb question but I'm having trouble using a simple for loop, the i value is increased... I believe it is because the for loop has not met the required conditions.. but not sure what's going wrong
var text = "";
var i;
for (i = 0.0; i >= 5 / 360; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
What went wrong: it does not print out anything...
The problem is the condition becomes false in the first instance of the loop , 5/360 would be 0.013888 which is less than 0.0 , So it would not enter to append the text which you are trying to do. So the loop exists and the object text has only the initial value which was initialized.
For example , if you change the snippet as below it would generate a text:
for (i = 0.0; i <= 5/360 ; i++) {
text = text + "The number is " + i + "<br>";
}
The number is 0
So Kindly check the condition as per you requirement in order to generate text
The condition for your loop is that i >= 5 / 360, which is not true when the loop starts. I recommend i <= 5 / 360
++ increments by one. Since the expression to be evaluated is less than one, try incrementing by a lesser value using +=.
For example:
var text = "";
for (var i = 0.0; i <= 5 / 360; i+=.005) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
<div id="demo"></div>
For more info, see these JavaScript references:
for statement
addition assignment
for ([initialization]; [condition]; [final-expression])
Operator: x += y
Meaning: x = x + y
there are 3 conditions in for loop as
1.initial value ex i=0
2.until which value loop should iterates ex i<=10
3.should vale has to be increment ++ or to be decreases -- after each iterations
in above given condition middle condition is wrong, it gets false value from its 1st iteration hence it is not able to complete even 1st iteration
var text = "";
var i;
for (i = 0.0; i <= 5 / 360; i++) {
text += "The number is " + i + "<br>";
console.log(text)
}
Related
According to Mozilla, the Addition Assignment operator
adds the value of the right operand to a variable
and assigns the result to the variable. The types of the two operands determine the behavior of the addition.
Here's the behavior of the addition:
If both expressions are numeric, then add.
If both expressions are strings, then concatenate.
If expression is numeric and the other is a string , then concatenate.
Basically, text+=i is the same as text = text + i; that is a fact.
Ok, if the above is true, then why in Code Version 2 below when I variable-ize the string "The number is " to the variable text,
doesn't it write the string each time with the new number as code version 1 does?
And for the answer I don't want another way to write it. I need to figure out why it doesn't work the same way if text+=i is the same as text = text + i.
I'm getting better at JavaScript every day, but believe it or not this simple += is holding me back from further understanding it because too many examples are using +=.
Here is the Code Version 1:
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text = "";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
Here is the Code Version 2 with var text variable-ized with the string "The number is ":
<h1>JavaScript Loops</h1>
<p id="demo"></p>
<script>
var text ="The number is ";
var i;
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
</script>
You are writing different code.
a = a + b is indeed the same as a += b.
var text = "";
text += "The number is " + i + "<br>";
Is the same as:
var text = "";
text = text + "The number is " + i + "<br>";
But it's not the same as:
var text = "The number is ";
text = text + i + "<br>";
Which is what you had.
For a question like this, it can be very helpful to use console.log to see what is happening.
var text ="";
var i;
console.log("First approach");
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
console.log("Second approach");
text ="The number is ";
for (i = 0; i < 5; i++) {
text = text + i + "<br>";
console.log("Iteration: "+i+" Text: "+text);
}
The code runs differently because in the first case you concatenate the entire string of "The number is ..." and in the second case, you initialize the string with "The number is " and then only concatenate the digits.
I am a newbie for java script programming. I want to print integers from 0 to 100. here is my code.
var outputAreaRef = document.getElementById("outputArea");
var i = 0; //Initialize counter
var number = 0;
while ( i <= 100) // Test Counter
{
number = number + 1 + "<br />";
i = i + 1; // Increment counter
outputAreaRef.innerHTML = number;
}
it prints digit 1 hundred times. but if i change the code like this,
number = number + i + ";
it will print from o to hundred. waht is the difference between the two codes?
thanks in advance
You are mixing strings with numbers. You need to do numerical computation in one variable and string concatenation in another. To increment number you can re-use i variable:
var outputAreaRef = document.getElementById('outputArea');
var i = 0;
var number = '';
while (i <= 100) {
i = i + 1; // numeric addition
number = number + i + '<br />'; // string concatenation
}
outputAreaRef.innerHTML = number; // it is ok to set html content only once
The code doesn't work because your output is number, and number is never changed and will remain as 0 because in the while loop, only i is changed.
Also change :
outputAreaRef.innerHTML = number;
to
outputAreaRef.innerHTML = outputAreaRef.innerHTML + number;
so that the whole innerhtml of the output area will not be replaced every loop.
Modify your while loop and it will work perfectly:
while ( i <= 100) {
number = i + 1 + "<br />";
i = i + 1; // Increment counter
outputAreaRef.innerHTML = outputAreaRef.innerHTML + number;
}
Working fiddle
var number became a String after first run and digit 1 concat to number afterward.
I've just started learning coding on code academy and I'm really new to this.
I'm trying to make this program ask the user for values which it adds to an array from which it calculates the sample standard deviation.
// This array stores the values needed
var figures;
getStandardDeviation = function() {
// I need at least two figures for a standard deviation
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
// Checks whether user wishes to add more values to the array
var confirm = prompt("Would you like to add another? (Y or N)").toUpperCase();
// I can't figure out why the following if statement is not executed
// It checks whether the user wishes to add more values and adds them to the array
// If not it breaks the for loop
if (confirm === "Y"){
for ( i = 0; i === 100; i++){
figures[i + 2] = prompt("Enter a number:");
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
// The rest of the code works fine from here onwards
var sumx = 0;
var n = figures.length;
for(var i = 0 ; i < n ; i++) {
sumx += figures[i];
}
console.log("Sum = " + sumx);
var sumXsq = 0;
for( i = 0 ; i < n ; i++) {
sumXsq += (figures[i] * figures[i]);
}
console.log("Sum x squared = " + sumXsq);
var sxx = (sumXsq - (sumx * sumx)/n);
console.log("Sxx = " + sxx);
var v = sxx/(n - 1);
console.log("Variance = " + v);
var standardDev = Math.sqrt(v);
console.log("Standard Deviation = " + standardDev);
};
getStandardDeviation();
The program is supposed to ask me if I want to add more values to the array, then when I confirm, it gives me a prompt to add more values.
Currently, when I execute the program I input the numbers 56 and 67. The code then asks me if I wish to add more values, I then confirm this. Instead of letting me add more values it ignores this and calculates the standard deviation with the first two values (56 and 67).
The output is:
Sum = 05667
Sum x squared = 7625
Sxx = -16049819.5
Variance = -16049819.5
Standard Deviation = NaN
for ( i = 0; i === 100; i++){[...]} means
Set i to 0
If it's not true that i === 100 (that is: if i is not 100), end the loop
Do whatever I put inside the {} braces, once
Do i++
Back to 2
As the initial value for i is 0 and not 100, the code inside the loop is never executed. If you want it to go from 0 to 99, it should be for ( i = 0; i < 100; i++).
You don't actually need a for loop, though. A while loop would be better. A loop like while (true){[...]} would run until it hit a break statement. As you wouldn't have the i in that case, you could use figures.push(parseFloat(prompt("Enter a number:"))) instead (you should use parseFloat, as per what Vincent Hogendoorn said) . push adds a new value at the end of an array, so it's exactly what you need. Something like:
if (confirm === "Y"){
while (true){
figures.push(parseFloat(prompt("Enter a number:")));
confirm = prompt("Would you like to add another figure? (Y or N)").toUpperCase();
if (confirm === "N"){
break;
}
}
}
You could also change it so it doesn't ask if you want to stop if you don't have at least two values. That way you would be able to leave out that first part:
figures[0] = prompt("Enter a number:");
figures[1] = prompt("Enter a number:");
indeed your figures variable isn't defined as an array, like #James Donnely says.
Keep in mind you also fill in strings, so if you want to add up values you have to convert them to values.
you can use something like parseFloat for this.
if you don't use it, you sum up strings. 3+4 will be 34 instead of 7.
Your figures variable isn't defined as an array. Because of this figure[1] = prompt(...) never gets hit and a TypeError is thrown on var n = figures.length;.
Change:
var figures;
To:
var figures = [];
JSFiddle demo.
You can then replace the for loop you're using after if (confirm === "Y") with a recursive function:
// Push a user input number into the figures array
figures.push(prompt("Enter a number:"));
// Function to add a new number and ask if we want to add more
function addNewNumber() {
// Push a new user input number into the figures array
figures.push(prompt("Enter a number:"));
// Ask if the user wants to add another number
if (confirm("Do you want to add another number?"))
// If they do, call this function again
addNewNumber();
}
// Trigger the function for the first time
addNewNumber();
JSFiddle demo with recursion.
function StandardDeviation(numbersArr) {
//--CALCULATE AVAREGE--
var total = 0;
for(var key in numbersArr)
total += numbersArr[key];
var meanVal = total / numbersArr.length;
//--CALCULATE AVAREGE--
//--CALCULATE STANDARD DEVIATION--
var SDprep = 0;
for(var key in numbersArr)
SDprep += Math.pow((parseFloat(numbersArr[key]) - meanVal),2);
var SDresult = Math.sqrt(SDprep/numbersArr.length);
//--CALCULATE STANDARD DEVIATION--
alert(SDresult);
}
var numbersArr = [10, 11, 12, 13, 14];
StandardDeviation(numbersArr);
I have two arrays set up that I wish to multiply each value within each together. Then I want to get the total value in the form of a variable. I will post what I have below. I think my problem may be that I am not sure how to get each run of the code to add together?
var flatQty=[];
flatQty[0]= document.getElementById("flats1").value;
flatQty[1]= document.getElementById("flats2").value;
flatQty[2]= document.getElementById("flats3").value;
flatQty[3]= document.getElementById("flats4").value;
flatQty[4]= document.getElementById("flats5").value;
var flatWidth=[];
flatWidth[0]=document.getElementById("flatwidth1").value;
flatWidth[1]=document.getElementById("flatwidth2").value;
flatWidth[2]=document.getElementById("flatwidth3").value;
flatWidth[3]=document.getElementById("flatwidth4").value;
flatWidth[4]=document.getElementById("flatwidth5").value;
for (var i=0;i<5;i++)
{
var flatCharge=flatWidth[i]*2*flatQty[i];
}
document.getElementById("flatTest").innerHTML=flatCharge;
When I run the code nothing is printed into the id="flatTest".
Your problems is that you are redefining your flatCharge inside the loop, therefore it's not correct outside the loop. In addition, you are not adding the values, but replacing them on every iteration of the loop. Change the loop to this:
var flatCharge = 0;
for (var i = 0; i < 5; i++) {
flatCharge += flatWidth[i] * 2 * flatQty[i];
};
document.getElementById("flatTest").innerHTML = "" + flatCharge;
and it should work.
.value properties are strings, not numbers. so you should be careful how you handle them. Multiplication actually works for strings, but not for addition where the + operator performs concatenation instead.
There are numerous methods of converting from string to number:
+s - will convert the expression s into a number
parseFloat(s)
parseInt(s, 10) for whole numbers
The actual problem in your code is that you're overwriting the calculated value in each pass using the = operator instead of +=.
I suggest refactoring your entire code thus to avoid all of the repetition:
var flatCharge = 0;
for (var i = 1; i <= 5; ++i) {
var qty = +document.getElementById('flats' + i).value;
var width = +document.getElementById('flatwidth' + i).value;
if (!isNaN(qty) && !isNaN(width)) {
flatCharge += 2 * qty * width;
}
}
was hoping if anyone could help. I would like to be able to have it that whenever the arrays I pass into the function change it will display these values in a paragraph tag.
At the moment it doesn't rewrite it and I want it to display like it's steps (i.e 1. ... 2. ...) but it doesn't update the step number or take a new line either. This function is called in another function.
The code so far is:
//javascript code
//cred & grade are arrays
function breakdown(cred, grade){
var change = document.getElementById('bdown'); //'bdown' is the id of the <p>
var to;
var a = 1;
var x = 0;
for(var b = 0; b<cred.length; b++){
//alert(a)
to += a + ". (" + cred[b] + " x " + grade[b] + ")" + "<br /"; //show the step number and the values then take a new line
a++; //increment the step number
change.innerHTML=bdown.innerHTML.replace(change.textContent,to ); //wish to change <p>
}
}
//html code
// the paragraph wish to change
<div id="how"; style="color:white;display: none">
<p id="bdown"></p>
</div>
Using code:
var to = "";
for(var b = 0; b<cred.length; b++){
to += "(" + grade[b] + " x " + cred[b] + ") + ";}
... .getElementById('').innerHTML = to;
Expecting output with cred = [10, 20], grade = [11, 21]:
(10 x 11) + (20 x 21) <-- this expands when arrays have values added to them.
Actual output:
(undefined) <-- doesn't change
I don't have jquery running on my coding platform so javascript code would be really great :)
To do a list of numbered steps, you want to use the ol tag.
Obviously, you'll want to populate the ol tag with li tags :P
Have you tried a simplified version to see if it works? Something like this:
document.getElementById("bdown").innerHTML=to;