How to iterate through possible null values in javascript without errors - javascript

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);

Related

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);

Is there a function for retrieving last array's element value?

I have an array of inputs that accepts a range of 0 and 1. var array = [0,1,0,0,1];//that is not static
Is there a function for retrieving the last element of the array?
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user inputs
var b= 0;
let l = array.length;
for(b=0; b<l; b++)
if(array [l-1]==0)
document.getElementById('print').textContent = 'Last element is 0';
}//end function
P.S: I am editing this old and bad question in order to get give the community time to re-evaluate it.
Please try this
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user inputs
var b=0;
if(array[array.length-1] == 0)
document.getElementById('print').textContent = 'Last element is 0';
}
You could take the length of the array and reduce it by 1 and take the element at this position for checking. You need no loop for the access.
if (array[array.length - 1] === 0) {
Doesn't really need a function, you can even write it inline.
function last_element_is_0(arr){
return !arr[arr.length -1]
}
function myfn(){
var array = [1,0,0,0,1,0]; //that may change depending on the user input
if(last_element_is_0(array))
document.getElementById('print').textContent = 'Last element is 0';
}

Is it Possiable to call to previous increments of a variable?

for example lets say i have a loop that is doing basic counting, while the variable is less than 16 the loop will run and at the end of the loop you add 2 to the variable and add one to a "count" variable
what i want to know is if its possible to callback to any of the previous variables for either variable for example can i count all the times count % 2 === 0?
im not quite sure if once a variable makes any kind of change if all previous versions of that variable are gone
http://codepen.io/anon/pen/Gojoxm
var two = 0;
var count = 0;
while ( two < 16) {
two += 2;
count++;
};
console.log(count);
If I understand you right, then no, you cannot. When you assign a new value to a variable, the previous value is lost.
You have to either run this loop again or store intermediate values in an array:
var values = [];
var two = 0;
while (two < 16) {
two += 2;
values.push(two);
}
console.log(values.length); // the same result
Then, you will always be able to do whatever you want with these values.
For example, you can check if there were any odd values:
var anyOddNumbers = values.some(function(x) { return x % 2 === 1; }); // false

add values to one variable with for loop totalSum 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);

Get a limit on arrays (Javascript)

I've a problem with set a limit into my own lightbox for a gallery
<script>
var imagenumber = 0;
function btnleft(){
load = imagenumber-=1;
document.getElementById('lightboxcontent').innerHTML=imagelist[load];
}
function btnright(){
load = imagenumber+=1;
if (load==undefined){load=imagenumber-=1}
document.getElementById('lightboxcontent').innerHTML=imagelist[load];
}
</script>
Then the array
var imagelist=new Array(); // regular array (add an optional integer
imagelist[0]="image1.jpg"; // argument to control array's size)
imagelist[1]="image2.jpg";
imagelist[2]="image3.jpg";
When I click more then 3 times on the next button I got the error-message "undefined".
How should I do to get a limit on my arrays?
Try it with
function btnleft(){
var load = imagelist[imagenumber-=1];
if (load) // imagenumber in array boundaries
document.getElementById('lightboxcontent').innerHTML = load;
else
imagenumber = 0;
}
function btnright(){
var load = imagelist[imagenumber+=1];
if (load) // imagenumber in array boundaries
document.getElementById('lightboxcontent').innerHTML = load;
else
imagenumber = imagelist.length-1;
}
Yet, Arrays in Javascript have no limited size, they are more like (infinite) lists. You can hardly set a limit on their length - espcially not with the constructor, whose number argument is just for initialisation purposes.
You can use the length property of an array to check whether your index is in the array boundaries: i >= 0 && i < arr.length. My code just checks whether there is an item at that index (as your second function seems to intend, too) and resets the index otherwise.
I assume that clicking on the "next button" calls the btnright() function.
If that is the case then you are testing the wrong value for undefined. You could rewrite your function as:
function btnright(){
load = imagenumber += 1;
// Test the value at the index of the array, not your index variable.
if (imagelist[load] === undefined) {
load = imagenumber-= 1;
}
document.getElementById('lightboxcontent').innerHTML = imagelist[load];
}
Stylistically this is still no the best. Your load variable is not required since its value always duplicates imagenumber. You could refactor the function such:
function btnright() {
// If we have a new array value do something.
if (imagelist[imagenumber + 1] !== undefined) {
// Increment the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[++imagenumber];
}
}
function btnleft() {
// If we're not on the first image do something.
if (imagenumber !== 0) {
// Decrement the index and load the new image.
document.getElementById('lightboxcontent').innerHTML = imagelist[--imagenumber];
}
}

Categories