Sum not being calculated properly - javascript

The program should do the following: The user should input numbers on the input field on the right and should click compute. The value will be pushed in the array. This will be done X times. At this moment X is hardcoded to 5 but that is not the problem.
The problem is that after the last number is pushed in the array, the sum of the array will be calculated and put out on the webpage. The visualisation isn't a problem and I am pretty sure that the calculations are correct. I think that the problem is how the input is read or inputet in the array. I might be wrong about this though.
One last thing, the function in which everything is calculated is compute1.
EDIT: the actual error: Uncaught TypeError: Cannot read property 'value' of null
This is the entire source code:
<!DOCTYPE HTML>
<head>
<title>Asd</title>
<style>
.btn{
width : 30px;
}
.btn2{
width : 100px;
height : 40px;
}
</style>
</head>
<body>
<center>
<table>
<tr>
<td>Number of elements:</td><td><input type="number" id="textField" class="btn"></input></td>
<td>Please enter a number.</td> <td><input type="number" id="textFiledInp" class="btn"></input></td>
</tr>
</table>
<button class="btn2" onclick="compute1()" >compute</button>
<p id="output"></p>
</center>
</body>
<script>
//var eleNum = parseInt(document.getElementById("textField"));
var eleNum = 5;
var arr = new Array;
function compute1()
{
console.log("hi");
if(eleNum > 0)
{
eleNum--;
arr.push(parseInt(document.getElementById("textFieldInp").value));
console.log(arr[arr.length-1]);
}
else{
var sum = 0;
for(var i = 0; i < arr.size; i++)
{
sum+= arr[i];
}
document.getElementById("output").innerHTML = sum;
}
}
</script>

You have a typo in the id of your element:
id="textFiledInp"
...should be:
id="textFieldInp"
Otherwise getElementById() can't find the element and returns null, hence the error message you quote.
And your for loop is trying to use arr.size but it should be arr.length.
Presetting eleNum to 5 seems a bit strange, but I'm not entirely clear what you're trying to do there so I'm not sure what to advise. I suspect you just need to move the commented out line inside your function and add .value (and uncomment it):
eleNum = parseInt(document.getElementById("textField").value, 10);
And also, never use parseInt() without specifying the radix in the second parameter. This is particularly important for user-entered data. (Because otherwise the browser may interpret a value with a leading 0 as octal, and a leading 0x as hexadecimal.)

After fixing the typos in your HTML, you should change the code to this:
var eleNum = 5;
var arr = []; //see explanation
function compute1(value) {
console.log("hi");
if (eleNum > 0) {
eleNum--;
arr.push(parseInt(document.getElementById("textFieldInp").value || 0, 10)); // see explanation
console.log(arr[arr.length - 1]);
} else {
var sum = 0;
for (var i = 0; i < arr.length; i++) {
sum += arr[i];
}
document.getElementById("output").innerHTML = sum;
}
}
You were using new Array; instead of new Array(), the better way is to use bracket notation. Or, in your case, you can define an array based on the length given by the user(with the input) or even using yours number of elements. It would be new Array(eleNum).
Why || 0? Because if the input is not defined by the user(value is null) then it sums up 0, otherwise you'll have NaN; remember to specify radix in parseInt, see nnnnnn's answer.
See a working fiddle of this.

You have wrong ID of input:
<td>Please enter a number.</td> <td><input type="number" **id="textFiledInp"** class="btn"></input></td>
and you try to get element of id "textFieldInp":
document.getElementById("textFieldInp").value);
Change id="textFiledInp" to id="textFieldInp" and it should work.
And size is not correct property of javascript array. You should use length property in your loop.
If you want to push in arr the amount of numbers you've declared you should write something like this (I don't know if this is what you want):
function compute1()
{
console.log("hi");
if(eleNum > 0)
{
eleNum--;
arr.push(parseInt(document.getElementById("textFieldInp").value));
console.log(arr[arr.length-1]);
}
else{
var sum = 0;
for(var i = 0; i < arr.length; i++)
{
sum+= arr[i];
}
document.getElementById("output").innerHTML = sum;
}
}

As far as I can tell, your calculations are correct, but you're missing a bracket console.log(arr[arr.length-1)
It should be:
console.log(arr[arr.length-1]);

Related

Javascript print arrays

<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<script>
function myarray()
var points = [];
for (var i = 0; i < 10000; i++) {
points.push[Math.round(Math.random() * 10)];
document.write(myarray(points));
}
</script>
<<button onclick="myarray"> OK </button>>
</body>
</html>
I am a beginner with javascript. I want to create a page that displays random numbers from 0 - 10. I am struggling to print an array. Is there a simple solution to this?
You should call the function from outside the function, not in the loop.
The function can just return the array, you can print it in the caller.
points.push is a function, you call it with (), not [].
You're missing {} around the function body.
The function doesn't take any arguments.
function myarray() {
var points = [];
for (var i = 0; i < 100; i++) {
points.push(Math.round(Math.random() * 10));
}
return points;
}
console.log(myarray());
There are too many syntax errors in your code and thsi suggests that you need a proper tutorial than an answer. However, the following snippet shows the conventional way of doing what you want.
function myarray(){
var points = [];
for (var i = 0; i < 10; i++) {
points.push(Math.round(Math.random() * 10));
}
document.getElementById('mySpan').innerHTML = 'Randoms: ' + points.toString();
}
myarray()
<span id="mySpan"></span>
You have some syntax errors as well as logic errors.
As pointed out in comments, for loop isn't executed.
A function is defined like function myarray() {}
A function is called with () like this myarray()
Array.push() is a method that you invoke using ().
You also seem to have rogue < in the HTML.
You can use an HTML element (In this case a <output> to display the contents of Array. The join('') method converts array content to a string.
function myarray() {
const el = document.querySelector('output');
var points = [];
for (var i = 0; i < 10; i++) {
points.push(Math.round(Math.random() * 10));
}
el.innerText = points.join('');
}
<button onclick="myarray()"> OK </button>
Results: <output></output>
You need to call the function to get the result intended.
points is an array and push is a function so it can be called using ().
function myarray() {
var points = [];
for (var i = 0; i < 10000; i++) {
const randomNumber = Math.round(Math.random() * 10);
points.push(randomNumber);
}
document.write(points);
}
<button onclick="myarray()"> OK </button>
You also need to make an another element or tag so we can place and show the result of our random numbers.
And render the result using something like this:
document.getElementById('generate-number').innerHTML = random_array.
Next, if you render the array directly to an element, it will output with a delimiter, which is a comma ,. The sample output would look like: 2,6,2,1,6. So if you don't want any delimiter, you can remove it by using the .join() function: random_array.join('').
Here's a working example to try:
function generateArray() {
// Creates 10 random numbers in an array
const rand_num_arr = new Array(10).fill(null).map(e => Math.floor(Math.random() * 10));
// Converts array into a string using .join()
const rand_num = rand_num_arr.join('');
// Display the random number in your div element "#generate-number"
document.getElementById('generate-number').innerHTML = rand_num;
}
<div id="generate-number"></div>
<button onclick="generateArray()">Generate Random Numbers</button>
//Arrow Function Expression
const demo = () => {
var temp = [];
for (var i = 0; i < 100; i++) {
temp.push(Math.round(Math.random() * 10));
}
return temp;
}
console.log(demo());
//Normal Function Expression
function demo() {
var temp = [];
for (var i = 0; i < 100; i++) {
temp.push(Math.round(Math.random() * 10));
}
return temp;
}
console.log(demo());
I found few mistakes both in javascript and HTML side + 1 never to do mistake
Some points are already mentioned in the accepted answer but here are a few new ones.
JavaScript Part
In your function myarray you have not used curly braces {}. All the codes of a function lie inside it.
The push is an array method so use a small bracket () not square bracket with it.
You are calling myarray function inside myarray function which causes infinite recursion.
(A never to do mistake) - You wanted to print array on webpage, never use document.write method, because when document.write is executed after a webpage is loaded it overwrites everything on the page. Instead you can use console.log or select an element and inject data in it using innerHTML method. (shown in the code below)
To print an array in javascript you can use index value with the array name. You can parallel print array elements as it is being pushed it reduce execution time. See in the code.
<!DOCTYPE html>
<html>
<head>
<title>100-Numbers</title>
</head>
<body>
<<button onclick="myarray()"> OK </button>>
<p id="output"></p>
<script>
const output = document.getElementById("output");
function myarray() {
var points = [];
for (var i = 0; i < 10000; i++) {
points.push(Math.round(Math.random() * 10));
output.innerHTML += points[i]; // printing array
}
}
</script>
</body>
</html>
HTML Part
One can't say these mistake but rather some modifications (also there is a mistake in the button).
(mistake) When you added onclick event listener to the button then call the function there, by adding parenthesis otherwise function will not execute on button click. Ex: onclick="myarray" => onclick="myarray()"
You should not use angle brackets directly in HTML, it confuses the browser whether it is part of a tag or not. Instead use HTML entity. For < use < and for > use >
Also you can put script tag at bottom of body it looks clean.

Squaring each number in an array with dynamically added inputs

I'm trying to calculate the standard deviation of a set of data entered by a user into a form with dynamically added inputs. Thus far I have been able to calculate the sum of the elements in the array, but I cannot figure out how to square each element of the array. I have searched this forum, but trying suggestions from the only applicable result (Square each number in an array in javascript) did not seem to work. Here is a snippet of my code:
$(".calcSD").click(function() {
$("input[type=text]").each(function() {
arr.push($(this).val().trim() || 0);
sum += parseInt($(this).val().trim() || 0);
});
Where .calcSD is the button the user clicks to perform the calculation. Moreover, the length of the array is given by var number = arr.sort().filter(Boolean).length; as the script is intended to filter out any inputs that are left blank.
Also, if it make a difference, inputs are dynamically added to the array via:
$('.multi-field-wrapper').each(function() {
var $wrapper = $('.multi-fields', this);
$(".add-field", $(this)).unbind('click').click(function(e) {
$('.multi-field:first-child', $wrapper).clone(true).appendTo($wrapper).find('input').val('').focus();
});
So I ask: how would go about determining the square of each element in the resulting array?
The pow() method returns the value of x to the power of y (x^y)
|| in parseInt will use base as 0 if it returns falsey value
$(".calcSD").click(function() {
var sum = 0;
var arr=[];
$("input[type=text]").each(function() {
var squared = Math.pow(parseInt(this.value)||0, 2);
arr.push(squared);
sum += squared;
});
alert(sum);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="text">
<input type="text">
<button class="calcSD">Calculate</button>
I might not have followed you correctly, but couldn't you just multiply the value by itself as it's pushed to the array?
$(".calcSD").click(function() {
$("input[type=text]").each(function() {
arr.push(($(this).val()*$(this).val()).trim() || 0);
sum += parseInt($(this).val().trim() || 0);
});
Ultimately I wanted to be able to sum the squares of the elements in the array (as it is a part of calculating the SD) so I did this and it works:
var sumXsq = 0;
for(var i = 0 ; i <= number ; i++) {
sumXsq += parseInt(arr[i]*arr[i]);
}
but not quite as good as Rayon's answer.

Javascript beginner inquiry. Identified problematic line of code but dont know why it doesnt work

I want the function NumberAddition to take a string and return an array of each number in it. For example argument "abc64,$ 22, 22xyz0" should return array [64, 22, 22, 0]. The 4th line in my for loop is the problem.
It's purpose is to move i up the string after a number is indexed so that it doesn't go over the same number again. If I delete this line the rest works fine with the problem of course being the same number being counted over and over until I naturally passes over it.
Why, when this line is included, does only the first number get counted (in my example the return would be [64]). I am less interested in other ways to solve it than why this line is not functioning how I had imagined it to. Thank you!
function NumberAddition(str) {
var array = [];
var nextInt;
for(var i = 0; i < str.length; i++){
nextInt = myParseInt(str.slice(i,10));
array.push(nextInt);
if (nextInt != null)
i = str.indexOf(nextInt,i) + nextInt.length -1;
else
break;
}
// code goes here
return array;
}
function myParseInt(str){
for(var i = 0; i < str.length; i++){
if (!isNaN(str[i]))
return parseInt(str.slice(i));
}
return NaN;
}
Numbers don't have a length; strings do. nextInt.length always returns undefined, which means you're setting i to NaN. Try nextInt.toString().length instead.

JavaScript .join is not working

Here is my code:
board = [];
var rowsNum = 5;
var colsNum = 5;
function printBoard(board) {
for (row in board) {
document.write(" ").join(row);
}
}
function clearAndRestartBoard() {
board = [];
for (i = 0; i < rowsNum; i++) {
board.push("[ ]" * colsNum);
}
}
printBoard(board);
It does not throw an error, but it does not show up in my webpage. Do you know what I am doing wrong?
Just in case, here is the html without the css:
<!DOCTYPE html>
<html>
<head>
<link href="test.css" type="text/css"rel="stylesheet" />
<title> Test! </title>
</head>
<body>
<p id = "script"> <script src = "test.js"> </script> </p>
</body>
</html>
I am very new to JS so thank you so much for any help!
There are several issues there, but the main one is that you never call clearAndRestartBoard, and so board is empty, and so you never output anything.
Here's a list of all of the issues that I see off-the-cuff:
You never call clearAndRestartBoard.
Your code is falling prey to The Horror of Implicit Globals: Declare your variables.
You're using for-in to loop through an array. That's usually not a good idea, though there can be use cases for it; this answer outlines your various options for looping through an array.
"[ ]" * colsNum is NaN because * will convert both of its operands to numbers and then do mathematical multiplication. The string "[ ]" converts to NaN because it cannot be interpreted as a number, and then anything multiplied by NaN is NaN. It isn't colsNum blank arrays. To do that, you'd have to have a second loop creating the row arrays, pushing "[ ]" into them, and pushing those row arrays onto board.
You're using document.write. While that will work for simple experiments, it's not something you want to use in general.
You're calling join on the result of document.write, which I'm fairly certain isn't an array.
I would also suggest that you either use a global board, or always pass it as an argument, but not mix-and-match where one function uses the global and the other uses an argument.
You never output a line break between rows.
Here's a minimal update addressing those:
var board;
var rowsNum = 5;
var colsNum = 5;
function printBoard(board) {
board.forEach(function(row) {
document.write(row.join(""));
document.write("<br>");
});
}
function clearAndRestartBoard() {
var row;
board = [];
for (var r = 0; r < rowsNum; r++) {
row = [];
for (var c = 0; c < colsNum; c++) {
row.push("[ ]"); // If you really wanted the string [ ]
}
board.push(row);
}
}
clearAndRestartBoard();
printBoard(board);

Problem with using javascript to insert <input> tags in html

I am trying to take text that is in an array (one word per value) and insert it into html. All the code is here: http://jsfiddle.net/chromedude/r6wVq/3/.
Update:
My question is what am I doing wrong? It does not do anything which is weird.
Just for everybody who was wondering what this code is supposed to help me do is memorize long passages for school.
You have an infinite loop, that's why the browser crashes:
for (i = 0; i < text.length; i++) {
var currentText = text[i];
for (i = 0; i<blanks.length; i++){}
}
The second loop always resets the counter variable i to 0. If you have nested loops you have to use different variables. And use var to declare the variables as local, e.g.
for (var i = 0; i < text.length; i++) {
var currentText = text[i];
for ( var j = 0; j<blanks.length; j++){
}
}
Same for your most outer for loop!
I don't know exactly what you want to achieve with the code, but here are some comments:
var blankNum = Math.random(Math.floor() * (text.length / 2));
Math.random takes no parameter, but Math.floor does.
for (i = 0; i < blanks.length; i++) {
blanks is still empty at this point, so the loop will never run.
if (currentText==blanks[i]){
Are you sure that blanks[i] will contain text? The previous mentioned (never running) loop seems to add numbers to the array.
textPrelim = <input type="text"></input>
You get a syntax error here, you must enclose the string into quotes.
I fixed your fiddle: http://jsfiddle.net/yEKPt/1/
What was wrong:
for iterator scope (here)
This line (27) threw a syntax error:
textPrelim = <input type="text"></input> //Needs to be quoted.
Should be:
textPrelim = '<input type="text"></input>'; //Quoted.
You reversed Math.random and Math.floor (lines 8, 14). (See: Math.Random(), Math.Floor())
var blank = Math.random(Math.floor() * (text.length / 2));
Check out my revised version. I think it accomplishes what you were looking for?
With addition to Felix's answer, try to check your code at http://www.jslint.com for syntax errors and undeclared (implicitly global) variables.

Categories

Resources