How do I display messages using an array or object - javascript

I've created a random generator game and this is a RandomNumber() function that will display the message if the user keys in the correct or wrong number. Does anyone knows how to display the message using an array or object method? For example, "Your guess number 1 is 5 and it is too low", "Your guess number 2 is 23 and it is too high". So the maximum number a user have is 5 tries.
function RandomNumber()
{
if (!this.guesses)
{
this.guesses = 1;
}
else
{
this.guesses++;
if (this.guesses > 5)
{
document.getElementById("correct").innerHTML="No more tries";
document.getElementById("guessing").disabled=true;
return;
}
}
//get value from random number textbox
var lol=document.getElementById("guess").value;
//get new value from user
var ass=document.getElementById("textbox").value;
if(ass == lol)//if user guess correctly
{
document.getElementById("correct").innerHTML="Correct"
}
else if(ass!=lol)//if user guess wrongly
{
document.getElementById("correct").innerHTML="Not correct"
}
}

function getMessage(correctNumber, guess, guessNumber) {
const highOrLow = guess > correctNumber?"too high.":"too low.";
return `Your guess number ${guessNumber} is ${guess} and it is ${highOrLow}`;
}
const message = getMessage(3, 5, 1); // message now equals "Your guess number 1 is 5 and it is too high."
Explanation:
The first line const highOrLow = guess > correctNumber?"too high.":"too low."; creates the part of the string that says "too high" or "too low" using a ternary operator. If guess is too high then highOrLow will equal "too high.". It will equal "too low." otherwise. The second line uses javascripts string templating to create the final string. The ${variable} part of the string are replaced with the value of variable.
Keep in mind this function doesn't account for when "guess" and "correctNumber" are equal.
This doesn't use an array or object but there is no reason to use an array or object. If you really want to put it in an object then do:
var o = {message: getMessage(3, 5, 1)}
but I don't see why you would need to do that.

Related

math.random always returning 1 in array

So i ran the code about 50 times and each time it returned olg / 1 so What is wrong
alert("welcome to word unscrambler undscramble this")
console.log("i am not a distraction")
document.write("i am not a distraction either")
var r = ["pttoao","recme","logd","teey","olg"]
var g=Math.floor(Math.random() *+ 6);
if (g=="0") {select =("pttoao")}
else if(g=="1"){select=("recme")}
else if (g==2){select="logd"}
else if(g==3){select="dre"}
else if(g==4){select="olg"}
if(select=="pttoao"){realword="potato"}
if(select=="recme"){realword="creme"}
if(select=="logd"){realword="gold"}
if(select=="teey"){realword="yeet"}
if(select="olg"){realword="log"}
var awnser= prompt("unscramble "+select)
if(awnser==realword){alert("correct")
}else{
alert("incorrect")}
maybe it is that it cant randomly select words
Here's some code that works for any amount of words.
Notice the structure: array of objects, objects have the real word and the scramble of it.
The random is relative to the amount of words.
I've combined the prompt, the check, and the alert into one line.
"Simplify by complication..." :)
var words=[
{real:"potato", scrambled:"pttoao"},
{real:"creme", scrambled:"recme"},
{real:"gold", scrambled:"logd"},
{real:"yeet", scrambled:"teey"},
{real:"log", scrambled:"olg"}
];
var random=Math.floor(Math.random()*words.length);
alert(
prompt("Unscramble: "+words[random].scrambled)
==
words[random].real?
"Correct":
"Wrong"
);
var g=Math.floor(Math.random() *+ 6 )
should be replaced with following as array elements index starts from
zero and array "r" contains 5 elements
var g=Math.floor(Math.random() * 5);
if(select="olg"){realword="log"}
here, you have assigned "olg" value to select variable. Inside "if" condition assignment is simply returning assigned value which is "olg" that makes it true and executes realword="log"
It should be replaced with
if(select=="olg"){realword="log"}

While loop for odd or even

Ask user for a number. Determine if the number is even or odd. I have my constants set and using modulo to figure this out. However I am stuck in an infinite loop and can't figure out why. I have my if statement in the loop as well as a break statement to get out, but still in an infinite loop.
HAVE TO USE A WHILE LOOP
// declare constants
const MODULO = 2;
const EVEN = 0;
const ODD = 1;
// declare variables
var enteredNumber;
var result;
// prompt user to enter an even number
enteredNumber = prompt("Enter an even number: ");
// convert user input into a number
enteredNumber = Number(enteredNumber);
// determine result of modulo equation
result = enteredNumber % MODULO;
// while loop to check if enteredNumber is even or odd
while (result === EVEN) {
document.write(enteredNumber + " is an even number <br/>");
enteredNumber = prompt("Enter an even number: ");
enteredNumber = Number(enteredNumber);
result = enteredNumber % MODULO;
if (result === ODD) {
document.write(enteredNumber + " isn't an even number");
break;
}
}
You can essentially one-liner this thing. You're already checking stuff with the while.
document.addEventListener('DOMContentLoaded', () => {
while (!(parseInt(window.prompt('Enter an even number', '2') || '1', 10) % 2)) { };
});
Why this works
Javascript has 'falsy' and 'truthy' values.
window.prompt('Enter an even number', '2')
This code prompts the user for a number. The result is a string (or null, if the user blanks out the prompt).
<a string or null> || '1'
If the user blanked out the prompt, it will return null. In Javascript we can use the or operator to choose between two things. null || '1' reads from left to right. The first thing is falsy so it chooses '1'.
If the user entered a number (like 10), we would get the number they entered as a string.
Then we parse the string to a number with parseInt.
Take that result and use the modulo operator % to divide by the operand and return the remainder. When you divide by 2 the remainder will either be 0 or 1. These are falsy/truthy values.
while(0) evaluates to false and breaks the loop. while(1) evaluates to true and continues the loop.

Javascript prompt and alert inputting a number and it will loop and you will input numbers to get the average of it

I have below javascript code with loop but I can't get the average of it. I'm not sure what's wrong with my code. It's like the first prompt you will input a number and it will loop and you input numbers like how much you entered and you will get the sum of all the numbers and get the average of it after it's done. Here's the code that I have.
function show_prompt()
{
var n=prompt("Input a number: ", "Number here");
if (n==n)
{
var i=1;
do
{
var g=prompt("Input grade: " );
var grade=parseInt(g);
var total=grade+grade;
i++;
}
while(i<=n);
}
var average=(total)/n;
document.write("Average is: " +average);
}
Thanks in advance!
You are overriding your "total" variable in each interval with double the grade value.
var grade=parseInt(g);
var total=grade+grade;
should be changed to
var grade=parseInt(g);
total=total+grade;
Also, you need to initialize the "total" variable in the beginning of your code.
See demo code: http://jsfiddle.net/56ouvan3/1/
I would also recommend some input validation (such as checking that the number of grades requested to average are greater than 0, all grades are positive, etc.)
I think you wanted to accomplish something like that:
http://jsfiddle.net/3L8dL228/1/
Just replace the console.log with your own document.write.
Now, despite I totally hate using prompts and I'm not very used to them, here are you what I think you're missing in your script:
CONTROL: your "n" and "g" variables HAS to be an integers, so force the user to insert an integer.
Variables declaration: you're declaring total every single time you loop, therefore you're not storing anything at all.
To fix these, the very first piece of your code becomes this:
var n = prompt("Input a number: ", "Number here");
while (!parseInt(n) )
{
n=prompt("Input a number: ", "Number here");
}
In this way, you're asking the user to give you a NUMBER, but the script won't procede until it will effectively be able to parse an integer value.
Therefore, inputs like "hey", "hello", "foo", "bar", "baz" won't be accepted.
The second part of your code then becomes this one:
var i=1;
var total = 0;
do
{
var g = prompt("Input grade: " );
while (!parseInt(g)) {
g = prompt("Input grade: " );
}
var grade = parseInt(g);
total += grade;
i++;
}
while(i<=n);
var average=(total)/n;
console.log("Average is: " +average);
and console.log needs to be document.write in your case, but for testing purposes and because jsfiddle (of course) doesn't allow document.write you need to check your console to see the correct value.
What changes from your script to this one is that we are declaring total as a global variable, not as a local variable inside the do loop that will be reset each time you loop.
Next, we're using the same logic as the first prompt for the second one, because you want, again, an integer value, not a possible string like "hey".
After that, we're ADDING that value to the total variable, by not redeclaring it.
Finally, after the loop, we're dividing that global variable total by the global variable n, getting the average.
Try below code to get the average of the entered number.
numGrades = prompt("Enter number of grades to be entered: ");
//number of grades to be entered LOOP
for (index = 1; index <= numGrades; index++) {
numberGrades = prompt("Enter Grade " + index);
}
//Calculation
gradePointAverage = numberGrades / numGrades;
document.write("Your GPA is " + gradePointAverage );

Decomposition of Javascript Class and Function Calls

I am creating a class to convert an integer to a sentence in a natural language. I've got some basic checks going on to ensure that the number given is between -9999 and 9999. I feel like this works for the most part.
However, once the program reaches "this.convertSentence" - past the try/catch block and error checking, I'm wondering what the best practice is now to decompose the problem into the various function calls it will need to run through to get the job done.
What I'm planning on doing with this.convertSentence is doing some checking for number size, etc...and then sending the number off to separate functions to do more work and having them propagate a sentence to return. I'm not sure if I want a variable just within my class to work with or whether I should be passing a variable around for the sentence to build. Things like this I am wondering about.
/**
* A class for converting an integer to a natrual language sentence in Spanish.
* Accepts integers from -9999 to 9999
*
*/
function NumberToWord () {
this.getSentence = function(number) {
// Check for erroneous input. Accepts only -9999 thru 9999 integers
try
{
if(number === parseInt(number) && number > -10000 && number < 10000) {
return this.convertSentence(number);
}
else {
throw new Error("Argument is not an integer between -9999 and 9999");
}
}
catch(e){
console.log(e.name + " " + e.message);
}
};
this.convertSentence = function(number) {
return "This is where I'll start the logic for the sentence";
};
}
var numberToWord = new NumberToWord();
// Tests
console.log(numberToWord.getSentence(9999));
console.log(numberToWord.getSentence(-9999));
console.log(numberToWord.getSentence(10000));
console.log(numberToWord.getSentence(-10000));
console.log(numberToWord.getSentence(0));
console.log(numberToWord.getSentence(1.1));
console.log(numberToWord.getSentence(-9999.1));
console.log(numberToWord.getSentence(10001));
console.log(numberToWord.getSentence(-10001));
console.log(numberToWord.getSentence(5.5));
console.log(numberToWord.getSentence());
There are a few things I found amiss in your code:
You don't need a class. You simply want to convert a number to a sentence. Use a function.
Why are both getSentence and convertSentence public? Only getSentence should be public.
Since your class will (in all probability) only be instatiated once, use the singleton pattern.
Things I would do:
Because you want to make your code modular, I would use the module pattern.
You can delegate specific tasks to different functions, but keep them in a private namespace.
Here's the code:
Number.prototype.toWord = function () {
return function (lang) {
var number = this.valueOf();
if (parseInt(number) === number) {
if (number < 10000 && number > 10000) {
switch (lang) {
case "es":
return toSpanish(number);
case "en":
default:
return toEnglish(number);
}
} else throw new RangeError("Expected an integer between ±10000.");
} else throw new TypeError("Expected an integer.");
};
function toSpanish(number) {
// convert the number to Spanish
}
function toEnglish(number) {
// convert the number to English
}
}();
Then you can use it like this:
var number = 1337;
alert(number.toWord("es"));
Edit: I wrote a simple function which will do what you want. However it's in English. I don't know Spanish so you'll have to implement that yourself. Here's the demo: http://jsfiddle.net/XKYhx/2/
My thinking would be to check how many parts you are going to have to the sentence and build an array to match with the substrings. for example, in English anyway (I don't speak Spanish!)
as natural language you would say (minus) xxx thousand and xxx
since your number has a max / min of ~10000 / ~-10000,
in pseudocode:
var sign = ""
var wholeparts = new Array()
var mantissaparts = new Array()
if number < 0,
sign = "minus"
number = math.abs(number) // turn the number into a positive number now we have the sign
var whole = math.floor(number) //get whole number
var mantissa = number - whole //get the after decimal part if exists
if whole > 1000
wholeparts.push(math.floor(whole/1000)) //get the thousands part
wholeparts.push(whole - parts[0]*1000) // add the hundreds
else
parts.push(whole)
if mantissa.length > 0
do something similar for the mantissa to the mantissaparts array.
At this point you would have the sentence structure broken down then:
string sentance:
foreach (var part in wholeparts)
stringify and check each number, converting to human words depending on index, ie "seven" or "seventy", add each to the string.
if wholeparts.length > 1 : sentence = sentence + " thousand and"
then if you had a mantissa, sentence = sentence + "point" .. then and the mantissa as natural language.
Best breakdown I can think of would be:
method to convert a number (whole or mantissa) to an array,
method to convert the array to natural language, with a parameter saying if it is whole or mantissa for the different wording that would be used.
method that accepts a number in string form and returns the natural language equivalent
Hope that helps .. was thinking on the fly.

How to store more than 10 digit number in javascript using the var?

First of all,
What am i doing ?
I have to set the limit of emails in our product in webpage.It's handled with the javascript for validation.It handles upto 8 digit numbers fine. But in our QA team enters the more than 17 digit number in the text box of other email field.It throw the negative message.What can i do ???
My sample code is:
if(form.otherEmails) {
if(validEmailArray.endsWith(',')){
var otherEmailLength = validEmailArray.substring(0,validEmailArray.length-1).split(",");
var setLimitOtherEmail = window.parent.document.getElementById('setLimitOtherEmail').value;
if(setLimitOtherEmail == '-1'){
form.otherEmails.value = otherEmailLength;
}
else if(otherEmailLength.length <= setLimitOtherEmail){
form.otherEmails.value = otherEmailLength;
}
else{
alert("More than "+setLimitOtherEmail+ " " +"Recipient emailIds not allowed in this section.\nIf you want to send it to more recipients, Please create a Bulk Contact Group.");
form.otherEmails.focus();
return false;
}
}
else
form.otherEmails.value = validEmailArray;
}
This is due to the limit being a string, and when a string is being compared to a number (length) the number is coerced into a string, not the other way around.
These are then compared lexicographically - and lexicographically "9" is more (>) than "19".
You need to use parseInt(setLimitOtherEmail, 10) to get the value as a number before comparing them.
Try parsing each of the numbers into Integers before performing any comparison operations on them.
var setLimitOtherEmail = parseInt(window.parent.document.getElementById('setLimitOtherEmail').value);
Other than that are you certain otherEmailLength is actually the number that you want? From the looks of it you are taking the substring of validEmail array and splitting it on "," but it doesn't look like you actually get the length of the array. Try adding .length to the end of the value of otherEmailLength.
var otherEmailLength = validEmailArray.substring(0,validEmailArray.length-1).split(",").length;

Categories