Wonder why while not working as expected? - javascript

I expected the loop to run 3 times. Can someone tell me what am I doing wrong?
var text = "";
var x = 123;
while (x > 0) {
text += "<br>The number is " + x;
x=x/10;
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

You need to check against 1 instead of zero, because a positive number divided by another positive number is always greater than zero.
var text = "";
var x = 123;
while (x > 1) {
text += "<br>The number is " + x;
x /= 10;
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

I think what you are trying to do is print the number first than remove last digit.If that is the case than, Here x/10 do not return an Integer number that is why the loop is executing more than once. Try the following:
var text = "";
var x = 123;
while (x > 0) {
text += "<br>The number is " + x;
x=Math.floor(x/10);
}
document.getElementById("demo").innerHTML = text;
<p id="demo"></p>

Related

How to use padStart in a JS loop to output a triangle of Xs?

I am supposed to create a triangle of Xs as depicted in the link by using padString image of 20 lines of Xs starting with one X and incrementing by one X for each additional line
The hint they gave was that I am supposed to use something like...
let str = "";
str = str.padStart(i,”x”); // i is the loop counter
What I have so far is this...
let xShape = "x";
for (let counter = 0; counter <= 20; counter = counter + 1) {
xShape = xShape + "x"
}
document.getElementById("demo").innerHTML =
xShape.padStart(xShape, "x");
<p id="demo"></p>
But that doesn't write out 20 lines of Xs starting with the first line having only one X with each new line having an additional X. It only writes the last line of 20 Xs. How do I get it to write all 20 lines? I am a beginner, and am doing this to learn. Thank you so much for your help.
padStart takes the string passed to it, and pads the beginning with the first argument as many times as the second argument.
So you can add it to a loop and just pass it an empty string so it will always have an empty starting point.
let xShape = "";
for (let counter = 0; counter <= 20; counter++) {
xShape += "".padStart(counter, "x") + "<br>";
}
document.getElementById("demo").innerHTML = xShape;
<div id="demo"></div>
You'll have to collect output lines in the loop somehow. But your use of padStart is also wrong: the first argument should not be a string, but a number. It should actually be your loop counter.
let lines = [];
for (let counter = 1; counter <= 20; counter = counter + 1) {
lines.push("".padStart(counter, "x"));
}
document.getElementById("demo").innerHTML = lines.join("<br>");
<p id="demo"></p>
Note that the method repeat is more natural here:
let lines = [];
for (let counter = 1; counter <= 20; counter = counter + 1) {
lines.push("x".repeat(counter));
}
document.getElementById("demo").innerHTML = lines.join("<br>");
<p id="demo"></p>
In a more functional approach:
document.getElementById("demo").innerHTML =
Array.from({length:20}, (_, counter) => "x".repeat(counter+1))
.join("<br>");
<p id="demo"></p>

how to fixed the loop outcome with continue

I am trying to use a for loop for 10 questions with an if condition. The continue is used to pass the one which is not match with condition.
My purpose is to randomly come up 10 question equations which results should be integers, but my code gives me only correct condition with a variable number of questions.
When the condition is not met, it will pass current equation, therefore sometimes I have end up with only 5 or 7 questions because the other 5 or 3 did not pass the condition.
How can I make sure that number of random equation generate is always the same, so that if a the condition is not met, the function will redo random amount of actions to end up with 10 questions?
my code is :
<body>
<p>this is testing for random number meet creteria</p>
<button class = "button" onclick = "myFunction()">try me</button>
<p id = "demo">Thisis where to display question</p>
<script>
function myFunction() {
var quiz = "";
var xNumber;
var yNumber;
var sign = ["+", "-", "*", "/"];
for (var i=0; i<10; i++) {
var xNumber = Math.floor(Math.random()*10);
var yNumber = Math.floor(Math.random()*10);
var randomSign = sign[Math.floor(Math.random()*sign.length)];
var result = eval(xNumber + randomSign + yNumber);
if (Number.isInteger(result)) {
quiz += xNumber + randomSign + yNumber + "<br>";
} else {
continue;
}
}
document.getElementById("demo").innerHTML = quiz;
}
</script>
Change your loop to be conditional on getting the number of items you want.
var numQuestions = 10, counter = 0
while (counter < numQuestions) {
var xNumber = Math.floor(Math.random()*10);
var yNumber = Math.floor(Math.random()*10);
var randomSign = sign[Math.floor(Math.random()*sign.length)];
var result = eval(xNumber + randomSign + yNumber);
if (Number.isInteger(result)) {
quiz += xNumber + randomSign + yNumber + "<br>";
// increment your counter here since you've added another question
counter ++;
}
}

Tutorial or quick 'how to' with numbers and strings inside in loops

I'm getting unexpected results with the code below:
function myFunction() {
var text = "something";
var i;
for (i = 0; i < 5; i++) {
text += "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
The result is:
somethingThe number is 0
The number is 1
The number is 2
The number is 3
The number is 4
Why don't I get the result below?
somethingThe number is 0
somethingThe number is 1
somethingThe number is 2
somethingThe number is 3
somethingThe number is 4
Well, it's simple: you start with "something" and then add "The number is " + i + "<br>" on each step; you don't add any more "something". To get the result you've described, you have to start with "" (empty string) and add "something" + "The number is " + i + "<br>" in your loop, pretty straight-forward:
function myFunction() {
var text = "";
for (var i = 0; i < 5; i++) {
text += "something" + "The number is " + i + "<br>";
}
document.getElementById("demo").innerHTML = text;
}
<p>Click the button to loop through a block of code five times.</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>

Sum up html string numbers using javascript

Hello I have a function that returns numbers inside a <p> tag with the following format:
<p class="numbers">123 + 456 + 789</p>
Is there any way I can do another function or something in javascript to sum up all the numbers and store it into a variable?
Thanks!
// Grab the element
const para = document.querySelector('.numbers');
// Convert the text content to an array and
// make the text number values into actual numbers
const numbers = para.textContent.split(' + ').map(Number);
// Use `reduce` to sum the numbers
const total = numbers.reduce((p, c) => p + c);
DEMO
This should do it:
var string = "<p class="numbers">123 + 456 + 789</p>";
var numbers = string.split(">")[1].split("<")[0].split("+");
var i = 0;
var sum = 0;
while(i < numbers.length){
sum += parseInt(numbers[i]);
i += 1;
}
return sum;
You can use Array.prototype.reduce()
var n = document.querySelector(".numbers").textContent;
var nums = n.replace(/\s/g, "").match(/^\d+|[+-]\d+/g);
var res = nums.reduce((a, b) => Number(a) + Number(b));
document.body.innerHTML += `=${res}`;
<p class="numbers">123 + 456 + 789</p>
var x = document.querySelector('.numbers').textContent.split("+").map(Number);
var y = x.reduce(function(add,num){return add+num})
console.log(y);

Display all the values inside an array using a button [duplicate]

This question already has answers here:
how to append to a object with innerHTML
(7 answers)
Closed 6 years ago.
The function will display all the even numbers between starting number and ending number based on the step value.
For example, if I enter 1, 20, and 3.
I should have 4, 10, and 16 as even number.
I need to push all the numbers inside evenNum array into #result span.
Currently it seems to only display the last even number inside the array.
Further more, if I would like to display all even number in vertical line, how do I do it?
https://codepen.io/anon/pen/wgwaey
<body>
<div class="container">
<h1>Sample</h1>
</div>
<div class="container">
<label>Starting Number: </label>
<input id="startingNum" type="text">
<br>
<label>Ending Number: </label>
<input id="endingNum" type="text">
<br>
<label>Step: </label>
<input id="step" type="text">
<br>
<button onclick="playButton()" id="play">Display Evens</button>
</div>
<div class="container">
<p>Here are the even numbers between <span id="startNum"></span> and <span id="endNum"></span> by <span id="stepNum"></span>'s:</p>
<span id="result"></span>
</div>
</body>
JS:
<script>
function playButton(){
run();
}
function run(){
var x = parseInt(document.getElementById("startingNum").value);
var y = parseInt(document.getElementById("endingNum").value);
var z = parseInt(document.getElementById("step").value);
document.getElementById("startNum").innerHTML = x;
document.getElementById("endNum").innerHTML = y;
document.getElementById("stepNum").innerHTML = z;
var evenNum = [];
while (x < y){
if (x%2 == 0){
evenNum.push(x);
}
x += z;
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML = evenNum[i];
}
}
}
</script>
The problem is here:
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML = evenNum[i];
}
You need to move this out of the while loop and change it to
document.getElementById("result").innerHTML += ' ' + evenNum[i];
// ^ add to existing
Or, more simply, delete the for loop and put this after the while loop:
document.getElementById("result").innerHTML = evenNum.join(' ');
The mistake above is that you're continuously reseting the result's inner HTML, so the last element of even num is the only one displayed. Also, you don't need to be updating result inside of your while loop, you can do it once you're done looking. Try this out!
function playButton(){
run();
}
function run(){
var x = parseInt(document.getElementById("startingNum").value);
var y = parseInt(document.getElementById("endingNum").value);
var z = parseInt(document.getElementById("step").value);
document.getElementById("startNum").innerHTML = x;
document.getElementById("endNum").innerHTML = y;
document.getElementById("stepNum").innerHTML = z;
var evenNum = [];
while (x < y){
if (x%2 == 0){
evenNum.push(x);
}
x += z;
}
for (var i = 0; i<evenNum.length; i++){
document.getElementById("result").innerHTML += "<p>" + evenNum[i] + "</p>";
}
}

Categories

Resources