how to fixed the loop outcome with continue - javascript

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 ++;
}
}

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>

Ideas for how to catch the last index in a jscript for loop, where lengh of index is is unknown?

Consider the following for loop (and assuming we don't know 3 times table - i.e. how many results might occur).
<script summary>
function myFunction() {
var output_text = "";
var i;
for (i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if ("e.g. this is the last index?") {"e.g.then do this?"
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
}
</script>
Trying to 'output_text' as something like:
The number is 0
The number is 3
The number is 6
The number is 9
The number is 12
The number is 15
The number is the last 18
Any ideas for how to catch that last loop iteration.
This is just an example as actual application is a bit wordy - but the concept is the same.
I could run a count first to get index length, but wondered if there is an easier way.
Many thanks for anyone's time. Also first go at posting - any advice welcome.
Just add 3 to the current index and check if it exceeds 19.
function myFunction() {
var output_text = "";
var i;
const max = 19;
const factor = 3;
for (i = 0; i <= max; i++) {
if (i % factor === 0){
if (i + factor > max) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
return output_text;
}
document.write(myFunction());
If you have a number divisible by 3, perform a second check to see if 20 minus i < 3 and you'll know if it's the last number.
function myFunction() {
var output_text = "";
for (var i = 0; i < 20; i++) {
if (Number.isInteger(i/3)){
if (20 - i < 3) {
output_text += "This number is the last " + i ;
}else{
output_text += "The number is " + i + "<br>";
}
}
}
document.getElementById("out").innerHTML = output_text;
}
myFunction();
<div id="out"></div>
The better approach is to show result of current iteration in the next iteration. In this case, last iteration will not be handled in the loop. So, you can handle it after easily.

JavaScript - How would i add var into an array with prompts and get the average with a button

This is my code. I know that it is wrong but I need some help to start a prompt list. My goal is to get 4 marks with a button then you input and have it in an array. It then gets averaged and that gets shown with an alert.
<html>
<head>
<title>Quiz</title>
</head>
<body>
Average your marks
<button onclick="myFunction()">Start</button>
<script type="text/javascrypt">
var student = []
var student[0] = prompt("Name:");
var student[1] = prompt("mark=");
var student[2] = prompt("mark=");
var student[3] = prompt("mark=");
var student[4] = prompt("mark=");
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
function myFunction() {
if (confirm(student) == true)
}
</script>
</body>
</html>
i actually think you are almost there:
change every avArray to student. and the first time to var student = []
edit:
also write function instead of fuction
edit 2
finally: because you use var you define a variable. so only use var with var student = []
var student[0] is wrong because student is already defined. so use student[0] =
Because prompt always returns a string you want to use Number to make it a number that you can calculate with.
So your final code would look something like this:
var name = prompt("Name:");
var grades = [];
grades[0] = Number(prompt("mark="));
grades[1] = Number(prompt("mark="));
grades[2] = Number(prompt("mark="));
grades[3] = Number(prompt("mark="));
var average = (grades[0] + grades[1] + grades[2] + grades[3]) / 4;
function myFunction() {
confirm(name + ": " + average)
}
Average your marks:
<button onclick="myFunction()">Start</button>
You want to make sure that you are adding int values, not String values - which are the return result of prompt.
Try this:
// Forces the user to input an int by retrying until an int is input
function intPrompt(msg) {
while (true) {
var num = parseInt(prompt(msg));
if (!isNaN(num)) return num;
}
}
Now here's the code that will read 4 marks from the user and average them:
alert((intPrompt('mark 1') + intPrompt('mark 2') + intPrompt('mark 3') + intPrompt('mark 4')) / 4);
Quite a few errors, here are some I've spotted so far:
<script type="text/javascrypt">
Spell javascript correctly
var student[0] = prompt("Name:");
You use var only when defining the student the first time, remove it from the next appearances of student.
if (confirm(student) == true)
Student is an array, not a string. You will need to convert it to a string in some way to use it for confirm AFAIK.
var student[5] = student[1] + student[2] + student[3] + student[4] / 4;
I just tested this line out, and averaging doesn't work correctly, you need to prevent concatenation, maybe proper brackets.
Calculation of average is not the perfect one and you try to put everything into array, even if it does not belong there.
Check the example: http://codepen.io/anon/pen/rWxMEP
<html>
<head>
<title>Quiz</title>
<body>
Average your marks<button onclick=myFunction()>Start</button>
<script type="text/javascrypt">
let name;
let studentMarks = [];
const numOfMarks = 4;
let sumMark = 0;
let msg;
let myFunction = function() {
name = prompt("Name");
if (name.length !== 0){
for(i = 0; i < numOfMarks; i++){
msg = "Enter mark (" + parseInt(parseInt(numOfMarks)-parseInt(i) )+" left)";
studentMarks[i] = prompt(msg);
sumMark += parseFloat(studentMarks[i]);
}
alert(name + "'s average mark is "+ sumMark/numOfMarks);
}
}
</script>
</body>
</html>

How to add a tick mark based on a counter in Javascript

I'm making a simple game in HTML/Javascript where everytime a button or hyperlink gets pressed it adds 1 to a counter
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = count;
}
</script>
My question is is there a way to also add a tick (Ascii #10004) equal to the number in the counter. I'm sure this is an easy solve but I've never really used Javascript and this seems the easiest language to do this all in. I appreciate any help given
You can use the HTML decimal: ☑
Just replace the code:
document.getElementById("p2").innerHTML = count;
with the following code:
document.getElementById("p2").innerHTML = "&#9745 "+count;
Or you can use:
document.getElementById("p2").innerHTML = "&#10004 "+count;
The result will be like this:
✔ 5
here 5 is your count.
Yes you can. You even don't need a loop to concatenate ticks.
see jsfiddle demo
var count = 5; // count is already 5 for demo purpose
function countClicks() {
count = count + 1;
var ticks = Array(count+1).join("✔");
document.getElementById("p2").innerHTML = count+' '+ticks;
}
countClicks(); # 6 ✔✔✔✔✔✔
Yes, you can use the String.fromCharCode to convert ascii code to character.
Example to display continuos ticks equal to number of count:
<script type="text/javascript">
var count = 0;
function countClicks() {
count = count + 1;
var res = String.fromCharCode(10004);
var output = "";
for (var i = 0; i < count; i++) {
output += res+" ";
}
document.getElementById("p2").innerHTML = output;
}
</script>
This will do :
http://jsfiddle.net/oL83m567/1/
var count = 0;
function countClicks() {
count = count + 1;
var tick='';
for(var i=0;i<count;i++)
tick+= '&#x2714';
document.getElementById("p2").innerHTML = count + tick;
}
It sounds like you want to ADD another tick every time the thing is pressed? I would do it like this:
var count = 0;
function countClicks() {
count = count + 1;
document.getElementById("p2").innerHTML = document.getElementById("p2").innerHTML + '&#10004';
}
Or, slightly more efficiently:
var p2, count = 0;
function countClicks() {
count = count + 1;
p2 = document.getElementById("p2");
p2.innerHTML = p2.innerHTML + '&#10004';
}
In that case, count becomes unnecessary, unless you need it for something else.
I'd go for doing it with an array. Advantage of this is that you have the ticks stored as elements in the array and can manipulate them later e.g. change a chosen tick to a cross or have a button which removes a tick. Something like:
<script type="text/javascript">
var ticks=new Array();
function countClicks() {
ticks[ticks.length]="✔";
document.getElementById("p2").innerHTML = ticks.join("");
}
</script>

Compound assignment in Javascript resulting in NaN

I'm trying to get compound assignment working inside a loop in Javascript but it's throwing NaN at me and I don't know why as I'm still fairly new to Javascript. I am essentially trying to translate this into a jQuery-Validation custom method: https://github.com/pfwd/NHSNumber-Validation/blob/master/PHP/NHSValidation.class.php
Here's what I have so far
// Taken from https://github.com/pfwd/NHSNumber-Validation
var multipliers = {1:10, 2:9, 3:8, 4:7, 5:6, 6:5, 7:4, 8:3, 9:2};
var currentSum, currentNumber, currentMultiplier = 0;
//Get submitted NHS Number and remove whitespace
var givenNumber = value.replace(/\s+/g, '');
// Get length
var numberLength = givenNumber.length;
console.debug(givenNumber);
console.debug(numberLength);
// Number must be 10 digits in length
if (numberLength !== 10) {
return false;
}
// Check number
var checkNumber = value.substring(9);
console.debug(checkNumber);
// Loop over each number in the string and calculate the current sum
for (var i = 0; i <= 8; i++) {
var minus = i-1;
var plus = i+1;
currentNumber = value.charAt(i);
currentMultiplier = multipliers[plus];
currentSum += (currentNumber * currentMultiplier);
console.debug("i is " + i + " & current Num: " + currentNumber + " plus current multi: " + currentMultiplier + " plus " + currentSum);
}
var remainder = currentSum % 11;
var total = 11 - remainder;
console.debug(currentSum);
I don't know if the minus and plus vars are necessary but they're something I tried while trying to fix the NaN issue. A typical console debug line looks like this:
i is 0 & current Num: 1 plus current multi: 10 plus NaN
I've also tried this with the same NaN result:
currentSum = currentSum + (currentNumber * currentMultiplier);
var currentSum, currentNumber, currentMultiplier = 0;
is incorrect, and only initalizes currentMultiplier.
It should be
var currentSum, currentNumber, currentMultiplier;
currentSum = currentNumber = currentMultiplier = 0;
demo : http://jsfiddle.net/46dD5/

Categories

Resources