Javascript counter controlled loop using (while) error - javascript

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.

Related

How do I execute a for loop statement in javascript?

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)
}

javascript counter not displaying least number of doubles

Im trying to get a counter to register the least number of rolls it took to get a double and then when they play the 'game' again if they got an even lower number of doubles it replaces the first answer with the newer one.
count=0, doubles=0, lowest=10000000;
function Roll()
// Assumes: die images are in http://dave-reed.com/book/Images
// Results: displays a randomly selected image of a 6-sided die
{
var roll1, roll2;
roll1 = RandomInt(1, 6);
roll2 = RandomInt(1, 6);
document.getElementById('die1').src =
"http://dave-reed.com/book/Images/die" + roll1 + ".gif";
document.getElementById('die2').src =
"http://dave-reed.com/book/Images/die" + roll2 + ".gif";
count += 1;
if (roll1==roll2) {
doubles += 1;
}
if (doubles==3) {
alert("You got three pairs of doubles!!! It only took you " +count+ " rolls to get it! Now, go directly to jail, do not pass go, and do not collect $200");
doubles=0;
count=0;
}
if (doubles==3 && lowest>count){
lowest=count
document.getElementById('lowestLine').innerHTML = count;
}
document.getElementById('countLine').innerHTML = count;
document.getElementById('doublesLine').innerHTML = doubles;
}
You set doubles to 0 once it becomes 3 and then you check if doubles equals 3 which is never true.
It looks like you should put
if (lowest > count) {
lowest = count
document.getElementById('lowestLine').innerHTML = count;
}
inside first doubles === 3 check, but before you setting globals to 0.
Like this:
if (doubles === 3) {
alert("You got three pairs of doubles!!! It only took you " +count+ " rolls to get it! Now, go directly to jail, do not pass go, and do not collect $200");
if (lowest > count){
lowest = count
document.getElementById('lowestLine').innerHTML = count;
}
doubles = 0;
count = 0;
}

Why is this js loop being skipped in one instance?

I have a nested loop that will work most of the time, but for one particular case it does not run at all.
Here is the value that is failing: 1, 3-5, 7-10, 22
JS code:
document.getElementById("myButton").addEventListener("click", function () {
document.getElementById("msg").innerHTML = "";
// Get the short list
var list = document.getElementById("myIn").value;
var sublists = list.split(", ");
var Range = [];
var result = "";
var start; // for the nested loop
var end; // for the nested loop
for (var i = 0; i < sublists.length; i++) {
Range = sublists[i].split("-");
start = Range[0];
end = Range[Range.length-1];
Log("Range: " + Range); // Shows which parts of the sublist the program sees
for (var j = start; j <= end; j++) {
result = result + j + ",";
Log("Result in loop: " + result); // Show which parts make it inside the loop
}
}
result = result.slice(0, -1); // Takes off the extra comma at the end
Log("Result: " + result); // Shows result
});
When the failing value is entered, this is the result:
Range: 1
Result in loop: 1,
Range: 3,5
Result in loop: 1,3,
Result in loop: 1,3,4,
Result in loop: 1,3,4,5,
Range: 7,10 <--- Never goes inside the loop
Range: 22
Result in loop: 1,3,4,5,22,
Result: 1,3,4,5,22
I can't figure out why the 7-10 part is being skipped. Any help or explanation is greatly appreciated.
Here is the FIDDLE
You need use parseInt when work with integer here
start = parseInt(Range[0],10);
end = parseInt(Range[Range.length-1],10);
After splittng you get array with strings, and when you try compare "7" with "10" it compared as string and "7" always greater then "10", because char code for '7' greater than char code for '1' (first char in "10")
For converting to number you can use next function also: Number, parseInt or parseFloat
document.getElementById("myButton").addEventListener("click", function() {
document.getElementById("msg").innerHTML = "";
// Get the short list
var list = document.getElementById("myIn").value;
var sublists = list.split(", ");
var Range = [];
var result = "";
var start; // for the nested loop
var end; // for the nested loop
for (var i = 0; i < sublists.length; i++) {
Range = sublists[i].split("-");
start = parseInt(Range[0], 10);
end = parseInt(Range[Range.length - 1], 10);
Log("Range: " + Range); // Shows which parts of the sublist the program sees
for (var j = start; j <= end; j++) {
result = result + j + ",";
Log("Result in loop: " + result); // Show which parts make it inside the loop
}
}
result = result.slice(0, -1); // Takes off the extra comma at the end
Log("Result: " + result); // Shows result
});
// Log is my imitation of console.log()
function Log(stuff) {
var msg = document.getElementById("msg");
var newDiv = document.createElement("div");
newDiv.innerHTML = stuff;
msg.appendChild(newDiv);
}
<p>Try this value in the input: 1, 3-5, 7-10, 22</p>
<input id="myIn" type="text" />
<button id="myButton" type="button">Go</button>
<p id="msg"></p>
Since you are using a text input field all values from that field are strings. Then you use string manipulations that return more string values. You are never dealing with numbers. So Javascript will treat them as string values when testing if one value is greater than the other.
You can use the Number global object to safely cast a string value to a number. The benefit of Number over parseInt and parseFloat is if any part of the string is non numeric it will return a NaN value whereas the other two will return as much of the string as a number up to the first non-numeric character.
start = Number(Range[0]);

Splitting string 2 times with javascript

I am trying to break up this string by first splitting it into sections divided by ';'. Then I want to split those sections divided by ','. It is not working though and I am about to break my computer. Could someone please help me figure this out.
You can play around with my jsfiddle if you want... http://jsfiddle.net/ChaZz/
var myString = "Call 1-877-968-7762 to initiate your leave.,-30,0,through;You are eligible to receive 50% pay.,0,365,through;Your leave will be unpaid.,365,0,After;";
var mySplitResult = myString.split(";");
for(i = 0; i < mySplitResult.length -1; i++){
var mySplitResult2 = i.split(",");
for(z = 0; z < mySplitResult2.length -1; i++) {
//document.write("<br /> Element " + i + " = " + mySplitResult[i]);
document.write("<br/>Element" + z + " = " + mySplitResult[z]);
}
}
i is a number, as that's how you defined it.
To split the string, you need to access the i member of the Array.
var mySplitResult2 = mySplitResult[i].split(",");
If I may, if you have to split with character a then character b, the simplest would be :
string.split('a').join('b').split('b')

How do I convert an integer to decimal in JavaScript?

I have a number in JavaScript that I'd like to convert to a money format:
556633 -> £5566.33
How do I do this in JavaScript?
Try this:
var num = 10;
var result = num.toFixed(2); // result will equal string "10.00"
This works:
var currencyString = "£" + (amount/100).toFixed(2);
Try
"£"+556633/100
This script making only integer to decimal.
Seperate the thousands
onclick='alert(MakeDecimal(123456789));'
function MakeDecimal(Number) {
Number = Number + "" // Convert Number to string if not
Number = Number.split('').reverse().join(''); //Reverse string
var Result = "";
for (i = 0; i <= Number.length; i += 3) {
Result = Result + Number.substring(i, i + 3) + ".";
}
Result = Result.split('').reverse().join(''); //Reverse again
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
if (!isFinite(Result.substring(0, 1))) Result = Result.substring(1, Result.length); // Remove first dot, if have.
return Result;
}
Using template literals you can achieve this:
const num = 556633;
const formattedNum = `${num/100}.00`;
console.log(formattedNum);

Categories