add values to one variable with for loop totalSum Javascript - javascript

I have some values that come randomized to an variable.
Now i want to add every value to each other to get an total sum but the loop wont add them together.
The index variable work when i console log it. but not the total sum of a current value and the index value.
Any tips ?
This is the loop
// The indexValue is values I get from an array//
var indexValue = index; // Random number from 1 - 10
var totalSum = 0;
for(var x = 0; x <indexValue; x++){
var currentValue = index[x];
totalSum += currentValue;
}
console.log(totalSum);

I'm assuming since you're referencing index[x] that index is an array. If so, you are assigning the wrong value to indexValue. Try this:
var indexValue = index.length;
What this does is assign the length of the array to the variable indexValue. Now the for loop will run from 0 to n where n is the length of the array.
This should get you the values you need.
Hope this helps.
EDIT:
Below is a link to a jsFiddle I created with your example and the code explained:
jsFiddle
var index = [1,2,3,4,5];
var indexValue = index.length; // It's imperative that this is an array
var totalSum = 0;
for(var x = 0; x <indexValue; x++){
totalSum += index[x];
}
alert(totalSum);
The code above is a modified version of what you posted. The current value is not needed and has been removed. In this case, I created an array and stored the values in index. The length is computed, and the values are added together.
For the easy sake of testing, I changed console.log(totalSum); to alert(totalSum);. It will produce the same value just the same.
Just a reference note on console.log. Some browsers (mainly IE) who do not attach the debugger to the process automatically without a page refresh will through an error as console will be undefined. Here is a quick fix for that:
if(window.console && window.console.log) {
console.log(totalSum);
}
This checks that (a) the console object is attached to the global window object and (b) that the log object of console is attached to the console object.

you probably want something like this:
var sum = 0;
for (var i=0; i < index.length; i++) {
sum += index[i];
}
console.log(sum);

Related

How to iterate through possible null values in javascript without errors

I have up to 100 inputs on my screen, each one has either a numerical value, or is null (as its not been loaded onto the screen yet), I want to be able to take the value's of each of these inputs, and add them together to get a final value.
I have attempted this with a for loop, iterating through them, but once it gets to the null value ones, it returns 'NaN' error.
The first input is called 'Input1', the second 'Input2' etc...
My code below:
var val = 0; //assigning the final value OUTSIDE the for loop to stop it assigning itself as 0 every loop
for (var calc = 0; calc < 100; calc++) //less than 100 as of 100 inputs
{
var inputVal = $('#Input'+calc).val(); //grabbing each input on screen
var floatVal = parseFloat(inputVal); // converting each value to float
var finalVal = finalValue + floatVal; //takes the val of 0, and adds each input value onto it per loop
}
alert(finalVal);
This always returns 'NaN'.
If I set the for loop to 'calc < 2' for example, and load 2 inputs on the screen, it will work, so I'm assuming its because the other values are null?
Thank you
You can use the Number.isNaN(value) function to skip to the next loop iteration if the value is NaN.
Noticed in your code you declare val but then never use it, instead you declare a new finalVal on every loop. You should declare finalVal before the loop and add to it on every iteration, as such:
var finalVal = 0;
for (var i = 0; i < 100; i++)
{
var inputVal = $('#Input'+i).val();
var floatVal = parseFloat(inputVal);
if (Number.isNaN(floatVal))
{
continue;
}
finalVal += floatVal;
}
alert(finalVal);

Possible bug/misunderstanding of splice and slice

I have the next loop:
rolling_average_delta_follower=[];
followers=[32,34,36,38,40,42,44,46,48,50,52,54,56] // .length = 12
delta_followers=[50,52,54,56,58,60,62,64,66,68,70,72,74] // leng= 12
for (i = 0; i < followers.length ; i++) {
copie = delta_followers.slice(0); //creates duplicate of array delta_followers so I keep source original and not cut from it
copie.splice(7,i) // supposed to create an array that contains numbers from 50 to 64 -> next time the for executes it should go 52 to 66 and so on
console.log(copie)
for (i = 0; i < 8; i++) { // the 7 numbers added previously in the one array are getting summed up
totalx += copie[i]
}
rolling_average_delta_follower.push(totalx) // the sum of each array previously created is getting added to the main array where I need the data.
}
All good until I try to actually execute it, I end up with with a forever loop that I seem not to be able to escape.
Any help would be appreciated.
Thank you!
The problem is here:
for (i = 0; i < 8; i++) { // the 7 numbers added previously in the one array are getting summed up
totalx += copie[i]
}
By this code you override i used in the loop above.
Just use another variable name here. (j ?)
To make a copy of an array use the spread operator.
const copy = [...original];
To sum the values of an array use reduce.
const sum = array.reduce((sum, item) => sum + item, 0);

How to get loop value outside the loop

How to get the loop values outside the loop below example only prints the last value, For example if i wanted to print the loop results.
var result;
for (var i=0; i < 10; i++) {
result = i;
}
console.log(result);
Now how can i get the iterated values of the loop which are (1 to 10) in the console, because now i will only print the last value which is 10.
Put the log statement inside the loop where you set the value.
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result);
}
If you only want one output statement, you can concatenate your results before logging:
var result = "";
for (var i=0; i < 10; i++) {
result += i + " ";
}
console.log(result);
This will output 0 1 2 3 4 5 6 7 8 9 10
If you really want to log outside of the loop, wich is quite unnecessary in my opinion, may use an array? :
var result=[];
for (var i=0; i < 10; i++) {
result.push(i);
}
console.log(...result);
http://jsbin.com/gogeluhavi/edit?console
If you want result make to log magically, you may uses setters and a Proxy, so called Observables.
Enter result=10 into this console, ive implemented a Observable for you: http://jsbin.com/xacujabuwo/edit?console ; You could also paste your for loop...
The Above answears are correct but I would like to clear it up for you so you understand it too.
In your original code you have declared the variable "result" outside the loop, then at each iteration a value is assigned to your variable. So that first time around "result" = 0 , second loop and the "result" = 1 and so on.
When the the for loop is finished it reads the next line which is your console.log() statment with the variable "result". The last time the variable "result" was modified was inside the for loop at the 10th iteration and thats where you let it equal to the iterator,therefore the value of iterator is 11.
In order to display something at every iteration, the console.log() must be placed inside the loop. Check below example
var result;
for (var i=0; i < 10; i++) {
result = i;
console.log(result); // prints at every iteration
}
Since you didnt add jQuery tag I used only javascript.
Add a input hidden tag
<input id="idOfInput" style="visibility:hidden" type="text">
Set the desired value to the input
for (var i=0; i < 10; i++) {
result = i;
document.getElementById('idOfInput').value = result;
document.getElementById('idOfInput').change(); //note change() is to trigger the event
}
Add change event listener and get the value set in loop
var input = document.getElementById('idOfInput');
input.addEventListener('input', function()
{
console.log('input changed to: ', input.value); //you get the value here
});
hope it helps
var result=[];
for (var i=0; i <= 10; i++) {
result.push(i);
}
console.log("Result =>", result);

Higher Order Functions - Eloquent JS

I have been reading through Chapter 5 last night and throughout the morning and can't seem to get the higher order functions concepts to stick. Here are the examples:
//I understand this first function, I am including it because it is used in the next function.
function forEach(array, action) {
for (vari = 0; i < array.length; i++)
action(array[i]);
}
forEach(["Wampeter", "Foma", "Granfalloon"], print);
function sum(numbers) {
var total = 0;
forEach(numbers, function(number) {
total += number;
});
return total;
}
To my understanding the function sum is taking the argument numbers, which I believe comes in as an array? Now, when the forEach function is called (within sum), it takes the array numbers passed to sum and then it also takes an anonymous function?
I am really confused on what this anonymous function is actually doing. It is taking the parameter number but what else is it doing? Does this anonymous function imply that in that parameter, a function like print or show will be passed the parameter number? In other words it would look something like this
function([10,12,11]) {
var total = 0
forEach([10,12,11]), show(???)
//at this point it would iterate over the array, and use the action passed to display `//the pointer in the array. What I think is happening is that it is taking this pointer value and adding it to the total.` //
I have been trying to wrap my head around this example for a while, if anyone knows of a good explanation or any other documentation to read over I would greatly appreciate it, thanks!
The anonymous function is applied to every currently selected element. You can see better how this works if you unroll (execute stepwise) the loop (pseudocode, * means current element):
var total = 0;
forEach([*1, 2, 3]), fun(1)) => total = 0 + 1 = 1
forEach([1, *2, 3]), fun(2)) => total = 1 + 2 = 3
forEach([1, 2, *3]), fun(3)) => total = 3 + 3 = 6
You can rewrite the sum function like this:
// because there is no "pass by reference" in JavaScript for
// "simple" types, total must be wrapped in an object
// in order to return the sum through the parameter for the showcase
var result = { total: 0 }
function sum(numbers_array) {
for (var i = 0; i < numbers_array.length; i++) {
accumulate(result, numbers_array[i]);
}
}
function accumulate(acc, number) {
acc.total += number;
}
In this case the accumulate function does the same as the anonymous function. When the accumulate function is declared within the scope of the sum function, then the total variable is like global (it is known) to the accumulate function and then there is no need of the first parameter, so the function becomes like the one you already know:
var total = 0;
function sum(numbers_array) {
function accumulate(number) {
total += number;
}
for (var i = 0; i < numbers_array.length; i++) {
accumulate(numbers_array[i]);
}
}
Next step would be to extract and pass the accumulate function as parameter:
var total = 0;
function accumulate(number) {
total += number;
}
// notice, that JavaScript knows how many parameters your function expects
function sum(numbers_array, action) {
for (var i = 0; i < numbers_array.length; i++) {
action(numbers_array[i]);
}
}
What left is to extract the iteration and the code will look like this one in the book.
Let me see if I can explain this easily for you:
The forEach() function accepts two parameters, the first one called array is obviously an array or an array-like object, the second parameter called action is actually a function.
forEach() visits each element in the array passed to it and applies to each element in the array the function passed to it as the second parameter.
So forEach() calls the function passed to it named action for each element in the array and it gives the function the array element as a parameter.
The function sum(numbers) accepts an array as you have though, and it uses forEach() inside itself to calculate the sum of numbers in that array using the anonymous function.
Remeber that the anonymous function is called once for each element in the array passed to sum() so it actually sums the elements in the array.
In simple words : to make your code more generic and concise.
Ex:
Lets say we want to find the max element in an Array :
That's pretty easy and cool :
In java script we will write :
var array = [10,20,30,40,50,60]
function maxEle(array){
var max = array[0];
for(var i=0;i< array.length;i++){
if(max < array[i]){
max = array[i];
}
}
console.log(max);
}
So this will give me the maximum element in an array.
Now after few days, some one asked me that your max is working pretty cool, I want a function which will print the minimum in an array.
Again I will redo the same thing, which i was doing in finding Max.
function minEle(array){
var min = array[0];
for(var i=0;i< array.length;i++){
if(min > array[i]){
min = array[i];
}
}
console.log(min);
}
Now this is also working pretty cool.
After sometime, another requirement comes up : I want a function which will print the sum of all the elements of the array.
Again the code will be similar to what we have written till now, except now it will perform summation.
function sumArr(array){
var sum = 0;
for(var i=0;i< array.length;i++){
sum = sum + array[i];
}
}
console.log(sum);
}
Observation :
After writing these bunch of codes, I m rewriting almost the same thing in every function, iterating over the Array and then performing some action.
Now writing the repetitive code is not a cool stuff.
Therefore we will try to encapsulate the varying part i.e action viz min, max, summation.
Since its feasible to pass functions as arguments to a function in FPL.
therefore we will re-factor our previously written code and now write a more generic function.
var taskOnArr = function(array, task){
for(var i=0;i<array.length;i++){
task(array[i]);
}
}
Now this will be our generic function, which can perform task on each element of Array.
Now our tasks will be :
var maxEle = array[0];
var taskMaxEle = function(ele){
if(maxEle < ele){
maxEle = ele;
}
}
Similarly for min element :
var minEle = array[0];
var taskMinEle = function(ele){
if(minEle > ele){
minEle = ele;
}
}
Also for summation of Array :
var sum = 0;
var taskSumArr = function(ele){
sum = sum + ele;
}
Now we need to pass functions to taskOnArr function :
taskOnArr(array,taskSumArr);
console.log(sum);
taskOnArr(array,taskMinEle);
console.log(minEle);
taskOnArr(array,taskMaxEle);
console.log(maxEle);

Code doesn't work in foreach

Here is my code:
var divarray = document.getElementById("yui-main").getElementsByTagName("div");
var articleHTML;
var absHTML;
var keyHTML;
var bodyHTML = [];
for( var i in divarray) {
if(divarray[i].className == "articleBody"){
articleHTML = divarray[i];
for( var j in articleHTML ){
bodyHTML[i] = '';
if(articleHTML[j].className == "issueMiniFeature"){continue;}
if(articleHTML[j].className == "abstract"){absHTML = articleHTML[i]; continue;}
if(articleHTML[j].className == "journalKeywords"){keyHTML = articleHTML[i]; continue;}
bodyHTML[i] = articleHTML[i];
}
break;
}
i++;
}
The error I am getting is:
SyntaxError: Unexpected token var
I am using Google Chrome
The javascript for...in doesn't do what you would expect (which is enumerate through eleemnts in an array.
for...in in javascript will enumerate through the key/value pairs (or public variables) that make up the object (which isn't what you want).
You need to use a good, old fashioned for loop.
You can add this to your script:
Array.prototype.foreach = function (callback) {
for (var i=0; i < this.length; i++) {
callback(this[i]);
}
}
Then you simply do this:
myarray.foreach(function (currentItem) {
/*...do whatever with the currentItem...*/
});
I think you mistaking JavaScript for the functionality of PHP. JavaScript does not have foreach loops. JavaScript has for in, which is what you are incorrectly using and normal for loops. Use a standard for loop when dealing with arrays. You will need to use a for in loop with object literals because the index is not the simplicity of an incrementing positive integer.
In JavaScript a for loop has 3 parts in its argument separated by a semicolon as follows:
* start position of incrementor (optional if the variable is previous defined with 0 or a positive integer)
* end position of incrementor
* method of incrementation
In the following examples arrayName is value I made up for the name of an array:
for (; a < arrayName.length; a += 1) {
for (a = x + 1; a < arrayName.length + 3; a += 2) {
The for in loop argument has two required parts and a third part to prevent errors using an if condition:
* The value of an index to search for
* The name of the container in which to search
* The third part is an if condition
The following example will return the value supplied to the "book" index of the objectName object literal. objectName is a name I made for an example object literal:
for ("book" in objectName) {
if (objectName.hasProperty("book")) {
Why not use a traditional for loop instead? You're not really using an associative array here ...
That's not the right way to iterate over a collection.
You want a standard for loop, not a for..in loop
for( var i = 0, l = divarray.length; i < l; i++ ) {
There's something else, you then proceed to try to iterate over each element
for( var j in articleHTML ){
articleHTML at this point holds a reference to a single HTML node - not a collection or array of any sort.

Categories