Adding sum of an array but getting NAN - javascript

I'm trying to create a working time clock that allows me to input the number of hours I study everyday and get the total. Am I using parseInt wrong?
<html>
<head>
<title>Time clock</title>
<meta charset="utf-8">
</head>
<body>
<h1 id="header">Time clock</h1>
<p id="greeting"></p>
<input type="text" id="inp"/>
<button onclick="sumit()">Click</button>
<p id="hours"></p>
<script>
greeting.innerHTML = 'How many hours have you studied?'
function sumit(){
let text = parseInt(document.getElementById("inp").value);
let hours = (document.getElementById("hours"));
let total = 0
for (i = 0; i < 10; i++){
total += parseInt(text[i]);
hours.innerHTML = `You have studied a total of ${text + total} hours.`
}
console.log(total)
console.log(text)
}
</script>
</body>
</html>

The text variable is already defined and assigned the value of parseInt. So your total += parseInt(text[i]) is trying to index a number type (e.g. total += 123[0]) which isn't possible. Instead, you can just do total += text, or you can remove the parseInt call when you declare text and then do total += parseInt(text).

With minimal changes, this should work:
function sumit() {
let text = parseInt(document.getElementById("inp").value) || 0;
let hours = document.getElementById("hours");
let total = 0;
total += text;
hours.innerHTML = `You have studied a total of ${total} hours.`;
}
Explanation
parseInt can return NaN, so we use the || operator to let it default to 0
You don't need to loop over anything to sum the number
Even if you were looping over anything, you don't use reference indexes on numbers like you tried to do with text[i]
You don't need to add total to text multiple times

Related

How to find minimum value in an array created in other function?

I created a program which I display the array from input numbers by clicking the button "Add"(which have function "Push"). Then I created another button "What is minimum?" to find the minimum numbers among those and display it by function " Findmin"
But when I console it in Google it had the error Minimum is not defined
How can I access the array created in the function "Push" and use in function " Findmin" ?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Minimum Number</title>
</head>
<body>
<div>
<h3><b>Find Minimum Number</b></h3>
</div>
Number add to Array:<input type="text" id="num" name="inputNumber">
<button onclick="Push()">Add</button>
<br>Array Number is:&nbsp<span id="result"></span>
<br><button onclick="Findmin()">What is minimum?</button>
<span id="Min"></span>
<script>
const array = [];
const Min = document.querySelector("#Min");
function Push()
{
let x = document.querySelector("#result");
array.push(document.querySelector("#num").value);
x.textContent = `[`+array+`]`;
}
function Findmin(array)
{
let minimum = array[0];
for (let i =0; i<array.length; i++)
{
if(minimum > array[i]) minimum = array[i];
}
return minimum
Min.textContent = minimum;
}
</script>
</body>
</html>
Edit : I changed the arg passed in Findmin() to "array" . Now I have the error Cannot read property '0' of undefined at this code let minimum = array[0]; I still think the problem it is I don't know how to access in the array created in the first function not the const array = []
Edit2 After all I think I have found my solution . My code work very well even if I input 2 same numbers to the array. For example : I input 34,34,567,9 then the result will return 9. I will post my changed code here. If anyone have any idea on how to make my code easier to read then you're very welcome!
function Findmin()
{
let minimum = document.querySelector("#num").value[0];
for (let i =0; i<document.querySelector("#num").value.length; i++)
{
if(minimum >= document.querySelector("#num").value[i])
minimum = document.querySelector("#num").value[i];
}
Min.textContent = minimum;
I think this will be a easier approch
const array = [];
const Min = document.querySelector("#Min");
function Push() {
let x = document.querySelector("#result");
array.push(document.querySelector("#num").value);
x.textContent = `[` + array + `]`;
}
function Findmin() {
Min.textContent = Math.min(...array.map(Number));
}
<div>
<h3><b>Find Minimum Number</b></h3>
</div>
Number add to Array:
<input type="text" id="num" name="inputNumber" />
<button onclick="Push()">Add</button>
<br /> Array Number is:&nbsp
<span id="result"></span>
<br />
<button onclick="Findmin()">What is minimum?</button>
<span id="Min"></span>
You return minimum before setting Min's textContent to minimum. Returning exits the function - further code is not executed.
Instead, set the textContent before returning:
const array = [];
const Min = document.querySelector("#Min");
function Push() {
let x = document.querySelector("#result");
array.push(document.querySelector("#num").value);
x.textContent = `[` + array + `]`;
}
function Findmin(arr) {
let minimum = array[0];
for (let i = 0; i < array.length; i++) {
if (minimum > array[i]) minimum = array[i];
}
Min.textContent = minimum;
return minimum
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Find Minimum Number</title>
</head>
<body>
<div>
<h3><b>Find Minimum Number</b></h3>
</div>
Number add to Array:<input type="text" id="num" name="inputNumber">
<button onclick="Push()">Add</button>
<br>Array Number is:&nbsp<span id="result"></span>
<br><button onclick="Findmin()">What is minimum?</button>
<span id="Min"></span>
</body>
</html>
you did it very will actually
but your problem is that you return minimum before Min.textContent = minimum
another good way is to use sort the select first index 0
const array = [];
const Min = document.querySelector("#Min");
function Push()
{
let x = document.querySelector("#result");
array.push(document.querySelector("#num").value);
x.textContent = `[`+array+`]`;
}
function Findmin(arr)
{
let minimum = (array.sort((a, b) => a - b))[0];
Min.textContent = minimum;
return minimum
}
<div>
<h3><b>Find Minimum Number</b></h3>
</div>
Number add to Array:<input type="text" id="num" name="inputNumber">
<button onclick="Push()">Add</button>
<br>Array Number is:&nbsp<span id="result"></span>
<br><button onclick="Findmin()">What is minimum?</button>
<span id="Min"></span>
function Findmin(arr)
{
Min.textContent = Math.min(...arr);
}
For more information =>
https://medium.com/#vladbezden/how-to-get-min-or-max-of-an-array-in-javascript-1c264ec6e1aa

Random number generator wont work with parseInt?

I've got this function that does a random number between 100 and 1 in JS and it adds it to the Score keeper, but the score keeper wont work. I even added parseInt for it to convert it from a string to an actually numbers int but it gives me NaN. But when I remove parseInt it gives me stacked numbers. Example: 50 + 100 will become 50100 not 150. Is there something wrong with the code? Here is the HTML and JS
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title></title>
<link rel="stylesheet" href="pets.css">
</head>
<body>
<div>
<h1>Score Keeper</h1>
<button onclick="randGen()">Random Numbers</button>
<p id="paragraph"></p>
</div>
<h2 id="score"></h2>
<script src="pets.js"></script>
</body>
</html>
const scoreKeeper = document.getElementById('score');
scoreKeeper = 0;
function randGen() {
const p = document.getElementById('paragraph');
const generatedNumber = Math.floor(Math.random() * 100) + 1;
let currentNumber = parseInt(scoreKeeper.innerText) ?? 0
if (generatedNumber > 0) {
p.innerHTML = `Your number is: ${generatedNumber}`
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
return scoreKeeper;
}
}
Its a simple javaScript mistake. You are overwriting const. The aspect of const is that the value can NOT be overwritten. change it to let.
Also, you get an element document.getElementById("score") but then automatically overwrite it as 0. Also also, doing parseInt(scoreKeeper.innerText) ?? 0 checks if you can parseInt the innerText rather then if the innerText exist. You should check if it exist first and then parseInt it.
let scoreKeeper = document.getElementById("score");
function randGen() {
let p = document.getElementById("paragraph");
const generatedNumber = Math.floor(Math.random() * 100) + 1;
let currentNumber = scoreKeeper.innerText
? parseInt(scoreKeeper.innerText)
: 0;
if (generatedNumber > 0) {
p.innerHTML = `Your number is: ${generatedNumber}`;
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
}
}
Also, the return in this case in not needed. You do not return a value to any other function or place. You are modifying your h2 and p inner text directly from the function.
EDIT
You can make the code more readable and using less global variables by making an if check to check if the value is what you do not want and just do an empty return, and move the let scoreKeeper inside the function. Declare all other variables, besides the generatedNumber, after the check and return to only create variables and use up memory if the conditions are met.
function randGen() {
const generatedNumber = Math.floor(Math.random() * 100) + 1;
if (generatedNumber <= 0) return;
let scoreKeeper = document.getElementById("score");
let p = document.getElementById("paragraph");
let currentNumber = scoreKeeper.innerText
? parseInt(scoreKeeper.innerText)
: 0;
p.innerHTML = `Your number is: ${generatedNumber}`;
currentNumber += generatedNumber;
scoreKeeper.innerText = currentNumber;
}

Parse all numbers in a paragraph and sum them in JavaScript

I am doing the following JS exercise in which I need to parse all the numbers in the given paragraph and then sum all those numbers.
function get_sum() {
let s = document.getElementById('pc').textContent;
let matches = s.match(/(\d+)/);
let sum = 0;
for(let i = 0; i < matches.length; ++i) {
sum += matches[i];
}
console.log(sum);
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PC</title>
</head>
<body>
<p id="pc"> The cost of the processor is 9000.
The cost of the motherboard is 15000. The memory card is 6000.
The price of the monitor is 7000. The hard disk price is 4000.
Other item's cost is 6000. </p>
<button type="button" onclick='get_sum()'>Get Sum</button>
</body>
</html>
The output should be an evaluation of the expression of 9000+15000+6000+7000+4000+6000 i.e. 47000
Here:
function get_sum() {
let s = document.getElementById('pc').textContent;
let matches = s.match(/(\d+)/g);
let sum = 0;
for(let i = 0; i < matches.length; ++i) {
sum += Number(matches[i]);
}
console.log(sum);
}
added g for global,
added Number() because you get strings...
const pc = document.querySelector("#pc");
const totalBtn = document.querySelector("#btn-total");
totalBtn.addEventListener("click", e => {
const prices = pc.innerText.match(/\d+/g);
const total = prices.reduce(
(total, price) => (+price) + total, 0
);
console.log(total);
});
<p id="pc"> The cost of the processor is 9000. The cost of the motherboard is 15000. The memory card is 6000. The price of the monitor is 7000. The hard disk price is 4000. Other item's cost is 6000. </p>
<button id="btn-total">Calculate Total</button>
Just a small change in the regular expression.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>PC</title>
</head>
<body>
<p id="pc"> The cost of the processor is 9000.
The cost of the motherboard is 15000. The memory card is 6000.
The price of the monitor is 7000. The hard disk price is 4000.
Other item's cost is 6000. </p>
<button type="button" onclick='get_sum()'>Get Sum</button>
</body>
</html>
<script>
function get_sum() {
let s = document.getElementById('pc').textContent;
let matches = s.match(/\d+/g);
let sum = 0;
for(let i = 0; i < matches.length; ++i) {
sum += parseInt(matches[i]);
}
console.log(sum);
}
</script>

How to generate set of arrays when clicking button, without disappearing the first one?

Im trying to learn js. Im starting playing with array by generating 6 combination numbers. This is working but i dont know how to output another combinations when I click the button. Any comment is appreciated. THanks
function getRandomNumber() {
var x = document.getElementById("num1").value;
var y = document.getElementById("num2").value;
var arr = [];
while(arr.length < 8){
var myrandomnumber = Math.floor(Math.random(x) * y + 1);
if(arr.indexOf(myrandomnumber) === -1) arr.push(myrandomnumber);
}
if (x==""){
alert("Please enter a number");
}
else if (y==""){
alert("Please enter a number");
}
else{
document.getElementById("ok").innerHTML = arr;
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>RANDOM NUMBER JS</title>
<meta name="" content="">
<link rel="stylesheet" href="css/css/bootstrap.css">
<link rel="stylesheet" href="css/cssextra/csse1.css">
<script src="customscript.js"></script>
</head>
<body class="bg-light">
<br>
<p id="demo">Random Number</p>
<br><br>
<input type="number" id="num1" name="one"/ >
<input type="number" id="num2" name="two"/ >
<button onclick="getRandomNumber();">Generate random number</button >
<p id="ok"></p><br>
<p id="okok"></p>
</body>
</html>
Accumulate results
A easy yet crude solution would be appending the current text with <br> for line breaks:
const p = document.getElementById("ok");
p.innerHTML = p.innerHTML + (p.innerHTML === "" ? "" : "<br>") + arr.join(", ");
But this approach will notoriously perform badly as the text grows larger.
If you change the p elements into:
<div id="ok" class="text-container">
And replace the script's document.getElementById("ok").innerHTML = arr; into:
const p = document.createElement("p");
p.textContent = arr.join(", ");
document.getElementById("ok").appendChild(p);
And add css:
.text-container {
margin-top: 1em;
}
.text-container > p {
margin: 0;
}
Then you should have something working.
Also there are some things to address:
Math.random()
The function Math.random() does not take arguments, so your variable x does not have any effect.
If the intention is to x and y as a minimum and maximum value, try this from Math.random() - JavaScript | MDN:
function getRandomInt(min, max) {
var min = Math.ceil(min);
var max = Math.floor(max);
return Math.floor(Math.random() * (max - min)) + min;
}
The min is inclusive and the max is exclusive. If x = 0 and y = 10, and you want the range to be [0-10], you can do getRandomInt(x, y + 1).
Make sure min is not greater than max.
Prevent infinite loop
Your loop will get stuck if the amount of possible unique integers is smaller than the number of array elements required for it to end.
More user input semantics
Variables x and y are tested before writing out the numbers, but after they have already been used to generate the numbers. In other words, the number creation process should be moved into the else block.
innerHTML expects a string and you are setting the array.
use document.getElementById("ok").innerHTML = arr.join(' ');
this will concatenate each element in the array with a space as glue

Running total of single die - Javascript

I am trying to create an application that has a die, singular for dice, on the screen. When you click the die, it will roll and display a number. I also want to keep a running total of each roll.
So far I have it to where each time the button is clicked, the image randomly changes. I'm confused about how to keep a running total of the rolls, however.
Here is the code I have so far.
<html>
<head>
</head>
<body>
<script>
function displaydie() {
var total = 0;
var num = ("src",(Math.floor(Math.random()*6)+1) + ".jpg")
document.getElementById("die").setAttribute("src", (Math.floor(Math.random()*6)+1) + ".jpg")
}
</script>
<img id="die" alt="die"/>
<br/>
<input type="button" value="Click me!" onclick="displaydie()"/>
<span id="total"/></span>
</body>
</html>
Use a global variable to store the total value then add the value of the current dice to the total. For that you need to store the value of the current dice in a variable and use it for the image and to add.
var total = 0;
function displaydie() {
var num = (Math.floor(Math.random() * 6) + 1);
total += num;
document.getElementById("die").setAttribute("src", num + ".jpg")
document.getElementById("total").innerHTML = total;
}
Demo: Fiddle
You want to create a dictionary, and on each roll, add to the number of times you have rolled that number:
var rolls = {1:0, 2:0, 3:0, 4:0, 5:0, 6:0}
var total=0;
function displaydie()
{
var num= Math.floor(Math.random()*6)+1
rolls[num]+=1
total+=1
document.getElementById("die").setAttribute("src",num + ".jpg")
document.getElementById("total").innerHTML = "Total rolls: "+total+"\n"+"1: "+rolls[1]+" 2: "+rolls[2]+" 3: "+rolls[3]+" 4: "+rolls[4]+" 5: "+rolls[5]+" 6: "+rolls[5]
}
DEMO

Categories

Resources