convert array.push.(prompt()) into a number - javascript

when i run the program the browser tell me moy is NaN yet I took care to use .map(Number) to convert the array into a number . I need some help please.
var score = [];
var i = 0;
var choice = 0;
while(choice != null){
i++;
score.push(prompt("put the score number "+i));
score = score.map(Number);
choice = prompt("to continue click on ok to cancel click on cancel");
}
var sum = 0,moy;
for(a=0;a<=i;a++) {
sum = sum+score[a];
moy = sum/i;
}
document.write("you put "+i+" score(s) <br>and the average is"+moy);

you have syntax error in this line
for(a=0;a<=i;a++) {
define a variable like this
for(var a=0;a<=i;a++)

Related

Searching for number inside of an array

Forgive me, I am not quite skilled and fairly new to the language and programming practices. I am creating a button which prompts the user to enter a number once the number is entered, I create a for loop that iterates through the same amount as the number. For example, the user enters 4 and the screen will display 0 1 2 3 and then I have a button that asks the user to enter a number to see if that number exists in the previous array. So if the user entered 3 it would dispay "it exists" if they entered 5 it would display "number not found". Should I create an array to store the iterations and then run that array through a function that searches for the number. Looking for guidance, thank you for the help guys.
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var sn = parseInt(prompt("Search for number"),10);
for(var j = 0; j < sn; j++){
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>
Make your n variable global
Than compare if sn is higher than n
var n; // Make it global
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
n = parseInt(prompt("Please enter a number"), 10);
// Set up a string that will become the output.
var output = " ";
// loop through given number
for (var i = 0; i < n; i++) {
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber() {
var sn = parseInt(prompt("Search for number"), 10);
var isHigher = sn > n; // n is now accessible in this function
var message = isHigher ? "Not found" : "Number found!";
alert( message );
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick="findNumber()">Click!</button>
To search an array, use the indexOf() method of a JavaScript array. The original post gives an example populating the array with myArray[x]=x, creating options pointed out by other solutions. Presuming you want to search a more general case of an array, you could use indexOf directly or define a function that returns true or false:
function inArray(myArray, queryValue) {
return myArray.indexOf(queryValue) > -1;
};
Arrays in JavaScript are objects with some additional methods like pop(), indexOf(), etc. JavaScript objects are associative arrays; this solution only applies to Array objects. Array objects are constructed with the [] literal or the Array() constructor. Arrays can only have properties named by ints, unlike other JavaScript associative arrays. See Eloquent JavaScript.
In this theoretic example, it's true that you only need to check if the second number entered is smaller than the first number. If you want to search for a number in an array of any numbers, you can use the javascript indexOf function. See example below:
var arr = [1,6,77,888];
if (arr.indexOf(66) > -1) {
alert('number is in array');
} else {
alert('number is not in array');
}
There are a couple of ways to do this. For the sake of simplicity, I'll use a global variable here.
// A global variable to store user input
var userInput;
function getNumber() {
var el = document.getElementById("demo");
// Get the user's input and convert it to a number
var n = parseInt(prompt("Please enter a number"),10);
// Store the user's input to our global variable
userInput = n;
// Set up a string that will become the output.
var output = " ";
// loop through given number
for(var i = 0; i < n; i++){
// variable containing iterations
output += i;
//var numArray[i] = output;
}
//display iterations
el.textContent = output;
}
function findNumber(){
var el = document.getElementById("result");
var sn = parseInt(prompt("Search for number"),10);
// If number is within the range
if (sn < userInput) {
el.textContent = "it exists";
}
// If number is not within the range
else {
el.textContent = "number not found";
}
}
<button onclick="getNumber()">Click!</button>
<p id="demo"></p>
<button onclick ="findNumber()">Click!</button>
<p id="result"></p>

Javascript Random Name Guesser: Unresponsive Script Issues

This is my first post here and I am having trouble wording a question, so please bear with me as I have been on this issue for hours.
My friend and I have thought of a fun little function that is supposed to guess the user's name (through an <input> tag) in a certain amount of trials using the random number function to access string letters from an alphabet array numbered 0-25. The function is also supposed to give the user the number of trials it took to guess their name.
I keep getting a non-responsive script, (line 33 - The line containing the second "for loop").
var goal = document.getElementById("your_Name").value;
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var goalArray = goal.split("");
var trials = 0;
var guessArray = new Array();
var i;
var n;
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
while (goalArray != guessArray){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + guessArray + " trials to guess correctly";
Any help or attempt to help would be immensely appreciated!
In case anyone was wondering: This little idea of ours was to test the randomness of Javascript's random function through trials (he made the same program in MatLab, so we are going to compare results of the random functions from both languages).
goalArray != guessArray is always true since they are two separate arrays; even if they contain the same elements.
Since they appear to just be arrays of individual letters in a-z you could compare them with something like goalArray + '' != guessArray, because the toString() of the arrays will compare correctly.
This is how I eventually got it to work (by nesting the while loop and second for loop in another for loop):
var goal = document.getElementById("your_Name").value;
var goalArray = goal.split("");
var alphabet = ["a","b","c","d","e","f","g","h","i","j","k","l","m","n","o","p","q","r","s","t","u","v","w","x","y","z"];
var trials = 0;
var guessArray = [];
for (i = 0; i < goalArray.length; i++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
for (x = 0; x < goalArray.length; x++){
while (goalArray[x] != guessArray[x]){
trials++;
guessArray = [];
for (n = 0; n < goalArray.length; n++){
guessArray.push(alphabet[Math.floor(Math.random()*26)]);
}
}
document.getElementById("appendomatic").innerHTML = "It took " + trials + " trials to guess correctly";
}
}

Generate 7 unique random numbers in javascript

I have a project i'm working on.
I am to basically recreate lotto on the client side using javascript to generate 6 random numbers plus a bonus ball. as we all know, lotto numbers cannot be the same. this is where my question comes in.
Is it possible to remove a number that has been generated from being available in the next time round in the loop? This would make the function completely random. or do I need to still compare the number with the others in the array using indexOf?
for example, is the following possible?,
the first number that generates is 25,
the function then removes that number from being able to come up again.
so on...
Here is my js code,
function play(){
numbersArray = [];
for (i=0; i<=6;){
n = Math.floor(Math.random()*40)+1;
a = numbersArray.indexOf(n);
if ( a == "-1"){
numbersArray[i] = n;
i++;
var ballId = "ball"+i;
if( i != "7"){
document.getElementById(ballId).innerHTML = '<p>'+ n +'</p>';
} else {
document.getElementById("bonus").innerHTML = '<p>'+ n +'</p>';
}
} //end of if
}//end of for loop
}//end of play function
You need to create an object, in this case you could use an array, that holds all the possible numbers that can appear on the ball, we'll cal it n. Then you can use a while loop to keep picking numbers from that array, and splice/remove that specific number from the array on every iteration.
function play(n) {
var picks = [];
// Store possibilities in the numbersArr array
var numbersArr = [];
// n is the max number you can choose to appear on a ball
for ( var i = 0; i < n; i++ ) {
numbersArr.push(i);
}
while (picks.length < 7){
var randomIndex = Math.floor(Math.random() * numbersArr.length);
picks.push(numbersArr[randomIndex]);
numbersArr.splice(randomIndex, 1);
}
return picks;
}

Help with comparing to array values in JavaScript

I have developed this code with help from you guys here on stackoverflow. I have added an extra part to it where it compares two numbers from two different arrays, in this case offhire1 and pro2.
The problem is in my code where I have:
(offhire1[i].value > pro2[i].value)
It only allows me to contine if the numbers match i.e 100=100. But what I'm after is identifing any numbers that are greater than the value only 120 > 100. I have tested if the values are being passed and they are.
What is my mistake here can anyone suss it out.
function validateoffhire(form) {
var num1 = document.getElementById('num1');
var test2Regex = /^[0-9 ]+(([\,\.\- ][a-zA-Z ])?[a-zA-Z]*)*$/;
var accumulator = 0;
var num2 = num1.value;
var i=0;
var offhire1 = [];
var pro2 =[];
for(var i = 0; i < num2; i++) {
offhire1[i] = document.getElementById('offhire1' + i);
pro2[i] = document.getElementById('pro2' + i);
var offhire2 = offhire1[i].value;
// var pro3 = pro2[i].value;
if(!offhire2.match(test2Regex)){
inlineMsg('offhire1' + i,'This needs to be an integer',10);
return false;
}
else if (offhire1[i].value > pro2[i].value) {
alert("You entered: " + pro2[i].value)
inlineMsg('offhire1' + i,'You have off hired to many items',10);
return false;
}
else{
accumulator += parseInt(offhire2);
}
}
if(accumulator <= 0){
inlineMsg('num1' ,'You have not off Hired any items',10);
return false;
}
return true;
}
I'm not quite sure I follow you. If the numbers are the same, the statement won't match.
One issue in your code is that you're comparing strings, not numbers. You may want to change it to:
(parseInt(offhire1[i].value) > parseInt(pro2[i].value))

Search Array in JavaScript

I need to sort through a data set which as you can see I've assigned to the records variable. From that data I need to see if the zip code exists. If the zip code does not exist then I need to move it into the array (There of course will be duplicates) and continue checking the rest of the records, if it does exist I need to do nothing.
// Declare Array
var numbersArray = [];
// Variables
var records;
var zipCode;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;
output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();
output.innerHTML = "The unique zip codes are: ";
while (records.readNextRecord()) {
zipCode = records.getSampleZipCode();
for (index = 0; index < numbersArray.length; index++) {
if (zipCode === numbersArray[index]) {
var uniqueZip = false;
break;
records++;
}
if (zipCode !== numbersArray[index]) {
numbersArray.push(zipCode);
}
}
output.innerHTML += numbersArray;
}
}
You can simplify your for loop like so:
matchedZip = false;
for(i in numbersArray) {
if (numbersArray[i] === zipCode) {
matchedZip = true;
}
}
if ( ! matchedZip) {
numbersArray.push(zipCode);
}
Try plugging that into your while loop. If you have the array push inside of the for loop you're going to end up pushing each zip code in every time there is not a match.
Well, you didn't exactly ask a question, but I'll answer anyway :) The answer is that you should not use a normal array for this, but rather a map or associative array. Fortunately a plain Javascript object can be used for this:
var numbers = {};
// Variables
var records;
var numbers;
var index;
var output;
var outputMessageOne;
var outputMessageTwo;
var count = 0;
output = document.getElementById('outputDiv');
records = openZipCodeStudyRecordSet();
output.innerHTML = "The unique zip codes are: ";
while (records.readNextRecord()) {
var zipCode = records.getSampleZipCode();
numbers[zipCode] = 1; // just picking an arbitrary value
}
for (var zipCode: numbers) {
output.innerHTML += zip + " ";
}
The reason is that this way you don't need to loop through the existing data for each new input.

Categories

Resources