Trying to add numbers from an a array? - javascript

im getting a output of the temperature i entered instead of getting the sum. im trying to get both the total f and c. I tried making totalf and totalc arrays instead of var. I dont know if returning the value would help?
var totalf=0;
var totalc=0;
var output = [fahrenheit," ",celsius+ '\r\n'];
for(var i = 0; i < output. length ; i++){
totalf+=fahrenheit[i];
totalc+=celsius[i];
console.log(totalf[i],totalc[i]);
}
tried doing this
function average() {
sum=0;
for (let i = 0; i < document.getElementById('chart').value.length; i++) {
sum += document.getElementById('chart').value(output[fahrenheit]);
document.getElementById('chart').value=sum;
}

Related

I am running this javascript code but it is giving me an.. error please tell me what is wrong because I think the code is correct?

let marks_of_students = [100,100,40]
function FindGrade(marks) {
let sum = 0;
for (let i = 0;i <= marks.length; i++) {
sum += marks[i];
console.log(sum);
}
return sum;
}
console.log(FindGrade(marks_of_students));
I don't know why I'm seeing this NaN printing along side the sum. Someone please help what did I do wrong?
You are trying to loop over the mark_of_students array with a condition i <= marks.length which means the loop will try to find marks[3] in the last iteration which doesn't exist. You need to change the condition to i < marks.length to get the desired result.
let marks_of_students = [100, 100, 40]
function FindGrade(marks) {
let sum = 0;
for (let i = 0; i < marks.length; i++) {
sum += marks[i]
}
return sum
}
console.log(FindGrade(marks_of_students))
try to convert a object into a integer by command parseInt(object) to sum.
Im javascript concatenates, NaN is not a number;
Try to do this:
parseInt("1") + parseInt("1")
instead of 1 + 1

Invalid Javascript left hand side in assignment

Wondering why I'm getting invalid left hand side assignment. Doesn't my for loop iterate through the array of string characters, get its numeric value (ASCII) and add it to count and re-assign it to the variable?
function getCharNumber(string1, string2) {
let count1 = 0
let count2 = 0
let strArray1 = string1.split('')
let strArray2 = string2.split('')
for (let i = 0; i < strArray1.length; i++) {
strArray1[i].charCodeAt(0) += count1
}
for (let i = 0; i <strArray2.length; i++) {
strArray2[i].charCodeAt(0) += count2
}
console.log(count1, count2)
}
Reverse the order at call to String.prototype.charCodeAt(). Assign the result of the call to count1, count2
for (let i = 0; i < strArray1.length; i++) {
count1 += strArray1[i].charCodeAt(0);
}
for (let i = 0; i <strArray2.length; i++) {
count2 += strArray2[i].charCodeAt(0);
}
You're getting an error, like others have stated, because you're trying to assign a value to a number.
strArray1[i].charCodeAt(0) += count1
is functionally equivalent to
12 += count1
That doesn't work b/c you can't assign anything to the number 12. Instead, you need to increment directly
strArray1[i] = String.fromCharCode(strArray1[i].charCodeAt(0) + count1)

Javascript How To Concatenate Separate Characters Into One String In Array?

I wrote a code for a "Heads or Tails" game below and:
var userInput = prompt("Enter maximum number output: ");
function coinFlip() {
return (Math.floor(Math.random() * 2) === 0) ? 'Heads' ; 'Tails';
}
for (var i = 0; i < 6; i++)
{
var result = [];
result["randomNum"] = (Math.floor(Math.random()*userInput);
result["coin"] = (coinFlip());
}
I'm trying to count the sum of total heads and sum of total tails each with the code:
var headsCount = 0;
var tailsCount = 0;
for (var j = 0; j < result["coin"].length; j++)
{
if (result["coin"] == 'Heads')
headsCount++;
else
tailsCount++;
}
The only problem is that it's counting each characters of 'Heads' and 'Tails' in the result["coin"] array as separate (such as 'H'-'e'-'a'-'d'-'s') and not into a full string (like "Heads"). Thus, instead of increment by 1 each time the loop above runs, it increments by +5.
I want it to increment by +1 only.
How do I make it so that the code reads the full string stored in result["coin"] and not character-by-character?
EDITED -- changed the <2 to *2
var result = []; is inside the for loop, so it is being overwritten with an empty array each time. So when you try to loop over the results, there's one one item in it; the last one. Pull the result array out of the loop so that you can add to it in each iteration.
It seems userInput should be the number of times to loop. Not sure why you're putting it in result["randomNum"]. result is an array, not an object, so it only has integer keys.
Instead of adding the result of the coin toss to result["coin"] I think you mean to add it to the array, so after tossing it six times it might look like this: ["Heads", "Heads", "Tails", "Heads", "Tails", "Tails"]. You can do this by calling result.push with the coin toss output.
To get one of two results randomly, compare the output of Math.random() against 0.5, which is half way between the limits. Numbers less than 0.5 can be considered heads, while numbers greater than or equal to 0.5 can be considered tails.
Putting it all together, this is what I think you were going for:
function coinFlip() {
return Math.random() < 0.5 ? 'Heads' : 'Tails';
}
var result = [];
var userInput = parseInt(prompt("Enter maximum number output: "), 10);
for (var i = 0; i < userInput; i++) {
result.push(coinFlip());
}
var headsCount = 0;
var tailsCount = 0;
for (var j = 0; j < result.length; j++) {
if (result[j] == 'Heads')
headsCount++;
else
tailsCount++;
}
console.log(headsCount, "heads and", tailsCount, "tails");
All that being said, there are definitely areas for improvement. You don't need to loop once to build the results, then loop a second time to read the results.
You can count the number of heads/tails as the coins are flipped. For example:
function isCoinFlipHeads() {
return Math.random() < 0.5;
}
var numFlips = parseInt(prompt("How many flips?"), 10);
var heads = 0;
var tails = 0;
for (var i = 0; i < numFlips; i++) {
isCoinFlipHeads() ? heads++ : tails++;
}
console.log(heads, "heads and", tails, "tails");

Finding Products within large Digits

I have been working on a way to find products of 5 digits within a large number. For example, I have the number 158293846502992387489496092739449602783 And I want to take the first 5 digits (1,5,8,2,9) and multiply them, then the second, (5,8,2,9,3), multiply then, then the third... And so on. Then I want to find the largest of all of them I find, now I came up with the following code to solve this problem:
// I put the digit into a string so I can modify certain parts.
var digit = "158293846502992387489496092739449602783";
var digitLength = digit.length;
var max = 0;
var tempHolder;
var tempDigit = 0;
var tempArray = [];
for(var i = 0; i<=digitLength; i++){
tempHolder = digit.substring(i, i+5);
tempArray = tempHolder.split("");
for(var j = 0; j < 5; j++){
tempDigit += tempArray[j];
}
if(tempDigit > max){
max = tempDigit;
}
}
console.log(max);
It logs to the console A longer number than what I put into it, along with 10 undefined, no spaces. Can anyone figure out the problem here?

sum number values from localStorage while looping

I found the same examples over and over about how to sum values but I haven't been able to use it for myself. I have two sets of data saved in localStorage. The first values for both keys are numbers which I want to add together. I found many .each functions that do the looping but I want to do it while looking through the key/value pairs, have a variable contain the sum as the key/value pairs loop. So here's what I have:
$(document).ready(function(){
if(localStorage.length > 0){
for (var i=0, len=localStorage.length; i<len; i++){
var sum = 0;
var key = localStorage.key(i);
var val = localStorage.getItem(key);
var valu = val.split("*");
alert (valu[0]); //alerts twice 130 and 160
sum += valu[0]; //didn't do anything
sum += parseInt(valu[0]); //also didn't work
alert (sum);
}
}
});
So the two values are 130 and 160 and they alert out as the function loops...so how can I add them and have like a running total as it loops?
You need the var sum = 0; outside the loop, as follows:
$(document).ready(function(){
if(localStorage.length > 0){
var sum = 0;
for (var i=0, len=localStorage.length; i<len; i++){
var key = localStorage.key(i);
var val = localStorage.getItem(key);
var valu = val.split("*");
alert (valu[0]); //alerts twice 130 and 160
sum += parseInt(valu[0]); //also didn't work
alert (sum);
}
}
});

Categories

Resources