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

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

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

How to permanently change var?

So, I have a var set in a function and a array(called "card_idx) set up, and I want the var be set to 0 until a certain number is reached in the array but the number doesn't go up in order (1..2..3..4 extra). It jumps around depending on how the person plays ( so it can be like...1...2...2.1....5....3.2...). And I want the var to be set to 0 until a specific number is reached and then it is changed to 1.
I try having it set up like:
var x=0;
if(card_idx == 3.2){
x=1
}
but the moment there no longer on 3.2 it will change back to zero, how do i make it so it will stay 1?
While your example isn't complete enough to reproduce the problem, I imagine you may be running into trouble with variable scope.
JS variables are locally scoped to the function surrounding them, which works to your advantage here. If you declare x at the beginning of the function that goes through your data, the loop can modify it and the value will be retained after the loop completes:
function crunch(data) {
var x = 0;
data.forEach(function (item) {
if (item.index === 3.2) {
x = 1;
}
});
console.log(x);
}
If any item in data had an index of 3.2, x will be set to 1 and printed to the console at the end. The callback to forEach grabs x using closure, but this would work just the same with a for loop.
Using x within the loop, the value will not be reset until crunch returns. Every time crunch is called, x will be set to 0, may be set to 1 if an item has the right index, and will retain that value until the end of crunch.
Now, with forEach, if you were to declare x inside the loop callback rather than in crunch, it would reset every time:
function crunch(data) {
data.forEach(function (item) {
var x = 0;
if (item.index === 3.2) {
x = 1;
}
});
}
Because var operates at the function level, this will not keep its value and will be 0 for every item.
You could try this. Use an extra boolean to check if x has ever been set.
Be aware that your variables are outside the iteration.
var x = 0;
var hasSet = false;
// start looping
if (card_idx == 3.2 && hasSet = false) {
x = 1
hasSet = true;
}
Or maybe (if your question was more clear) this will work out too.
var x = 0;
// start looping
if (card_idx == 3.2 && x <= 0) {
x = 1
}

value method not working function callback

I am creating a small program that returns the results of a mathematical equation. I have a number input field with the ID and CLASS "value1" (I've attempted to manipulate using both) that allows the user to put in a number value. I have another number input field that is disabled with the ID and CLASS "result1" that displays the results of the equation.
I have a button with the ID solution1_btn that when clicked is suppose to initiate the "multiples" function callback which takes "value1" as an argument.
When I replace "value1" which a physical number e.g. 1000, the results of the equation appears in "result1" without pressing solution1_btn, however when i put "value1" as the argument and press solution1__btn it does not work.
Below is the section of JavaScript code that I have narrowed the problem to and HTML.
JS:
// declare Euler1 assign it to function with parameter num
// click button
var solution1 = document.getElementById("solution1_btn");
// user entered value
//var value1 = document.getElementById("value1");
var value1 = document.getElementsByClassName("result1")[0].value;
//console.log(value1);
// result input field
var result1 = document.getElementById("result1");
function multiples(num) {
// declare sum assign it value 0
var sum = 0;
// declare a for loop that iterates while the counter "i" is less than num
for (var i = 0; i < num; i++) {
// if statement test whether the division remainder of 3 and 5 are equal to 0
if (i % 3 || i % 5 === 0) {
// assigns the value of i to sum
sum += i;
var newSum;
result1.value = newSum;
newSum = sum;
};
};
// returns the value of sum from the function callback argument 1000 etc.
return newSum;
};
var fix = value1;
solution1.onclick = multiples(fix);
HTML:
<label for="value">Enter Value: </label>
<input id="value1" class="value1" type="number" title="value field" placeholder="e.g. 1000">
<button type="button" id="solution1_btn" title="solution 1 button">Enter</button>
<input id="result1" class="result1" type="number" disabled>
Gosh, there is quite a few problems with your code, I'll try to run through them all.
Referencing HTML elements
HTML elements can be referenced in many ways, as you have discovered. Generally, you should pick the most appropriate and stick with it. If you use an id and a class things get confusing quickly - espcially seeing as id's should be unique, but classes need not necessarily be so. In your case, I think you're safest to stick with id, and then always use document.getElementById.
Multiple boolean checks
Regarding this line of code
if (i % 3 || i % 5 === 0) {
You probably expect that that equates to "if i is divisible by 3 or 5", and that is a logical (and often misunderstood) part of boolean logic. In actual fact, you should think "if i is divisible by 3 or i is divisible by 5", which equates to the following in code
if ((i % 3) === 0 || (i % 5) === 0) {
Yes, unfortunately you need to repeat the === 0 part twice.
Variable scope
This one's a big subject, and there is plenty of other information on the subject, but suffice it to say that in your function newSum is defined only inside an if block, and is redefined every iteration of your loop, so it wont contain the sum as you may be expecting.
In any case, it's uneccessary, you should just return sum
function multiples(num) {
// declare sum assign it value 0
var sum = 0;
// declare a for loop that iterates while the counter "i" is less than num
for (var i = 0; i < num; i++) {
// if statement test whether the division remainder of 3 and 5 are equal to 0
if ((i % 3) === 0 || (i % 5) === 0) {
// assigns the value of i to sum
sum += i;
};
};
// returns the value of sum from the function callback argument 1000 etc.
return sum;
};
Event handlers
You are trying to set an event to occur onclick with this code
solution1.onclick = multiples(fix);
This attempts to add an event handler with the result of calling multiples - not multiples itself. You should assign the event handler a function, and assign the value of the field to the result of calling the multiples function.
solution1.onclick = function(){
result1.value = multiples(parseInt(value1.value,10));
};
Working example
Below is a working example of your code, hopefully helps you pull this all together.
var solution1 = document.getElementById("solution1_btn");
var value1 = document.getElementById("value1");
var result1 = document.getElementById("result1");
function multiples(num) {
// declare sum assign it value 0
var sum = 0;
// declare a for loop that iterates while the counter "i" is less than num
for (var i = 0; i < num; i++) {
// if statement test whether the division remainder of 3 and 5 are equal to 0
if ((i % 3) === 0 || (i % 5) === 0) {
// assigns the value of i to sum
sum += i;
};
};
// returns the value of sum from the function callback argument 1000 etc.
return sum;
};
solution1.onclick = function(){
result1.value = multiples(parseInt(value1.value,10));
}
<label for="value">Enter Value: </label>
<input id="value1" class="value1" type="number" title="value field" placeholder="e.g. 1000">
<button type="button" id="solution1_btn" title="solution 1 button">Enter</button>
<input id="result1" class="result1" type="number" disabled>
Here is a fiddle with you problem - I hope solved: http://jsfiddle.net/w0qvdqb2/
There are few different problems in your code, first:
solution1.onclick = multiples(fix);
this means that multiples method should execute and return value is assigned to variable solution1.onclick but solution1.onclick accept callback.
Than based on your comments condition hasn't beed written as it's described.
And mixing with inputs and outputs classes and ids.
Please review updated code.

Trying to get a while loop to alert/log a string 3 times but instead it only logs once

The tutorial I'm following says that I need to use a while loop to log to the console "I'm looping!" three times without actually calling the console.log command three times. This is what I have, however when I run it, it only logs the string once and if I call my loop function 5 or more times, then it doesn't log at all.
var count = 0;
var loop = function(count){
while(count < 4){
console.log("I'm looping!");
count++
}
};
loop(3);
The count argument you've declared in your function shadows the count variable outside the function. ("Shadows" = "hides", e.g., the argument makes the variable inaccessible by name.) Since you're passing in the value 3 for the argument, the loop only runs once, as 3 < 4 but then you incremented it and 4 < 4 is false.
If you want to use the count variable declared outside the function, change the name of your argument and/or don't provide one at all:
var count = 0;
var loop = function(){
while(count < 4){
console.log("I'm looping!");
count++
}
};
loop();
The first time you call loop, it will loop four times (once for 0, for 1, for 2, and for 3). Any subsequent calls won't loop at all (unless you change count).
If you want to loop up to a given number of times, but never let count be >= 4, use a different name for the argument:
var count = 0;
var loop = function(c){
var i = 0;
while(count < 4 && i < c){
console.log("I'm looping!");
count++;
++i;
}
};
loop(3);
The first time you call that, it will loop three times, once for 0, then for 1, then for 2. Then, i is == c and so the loop does not continue. If you called loop again, it would run up to one time, at which point count would be 4 and the loop body would never be run.

The minimum even value in the array

So, I have this program that asks for the minimum even value in the array and I have written the code but I seem to missed a loop. I will write the correct code but I hope someone would explain why is there a while loop
<HTML>
<HEAD>
<SCRIPT LANGUAGE = "JavaScript">
var number=new Array(10)
for(var i=0; i<number.length; i=i+1)
{
number[i] =window.prompt('enter number ','')
number[i] =parseFloat(number[i])
}
var y = 0
while (number[y] % 2 != 0) //get the first even number in the array
{
y = y + 1
}
//after you exit the while loop y will have the index of the first even number
var Min
Min = number[y]
for(var i=0; i<number.length; i=i+1)
{
if (number[i] % 2 == 0)
{
if(number[i]<Min)
{
Min= number[i]
}
}
}
document.write(Min)
</SCRIPT>
</HEAD>
</HTML>
So, this part
var y = 0
while (number[y] % 2 != 0) //get the first even number in the array
{
y = y + 1
}
//after you exit the while loop y will have the index of the first even number
I'm finding it hard to really grasp this loop and if I might ask: is there another way to find the minimum value in an array?
Many thanks!
The while loop sets the first value of Min so that subsequent comparisons work. Here's a far
simpler and faster way to do the same thing:
var min = Infinity; // Start with the biggest number possible
for (var i=myArray.length;i--;){
var val = myArray[i];
if (val<min && val%2==0) min = val;
}
This is faster because—unlike the original code—this doesn't iterate over the first non-even values twice. It would be roughly equivalent in speed if the for loop in the original started at index y, i.e. for (var i=y+1;i<number.length;++i)
It's also very slightly faster because the for loop caches the length of the array instead of looking it up each time, and because it only looks up the value in the array once each loop, not three times. Modern JavaScript runtimes like V8 can optimize naive code to behave similarly, however, so this is not a very important point.
Edit: For fun, here's a modern, functional programming approach:
var min = Math.min.apply(Math,myArray.filter(function(n){ return n%2==0 }));
The above uses Array.filter to create a new array of just the even-valued items, and then uses Function.prototype.apply to pass the array of values as parameters to Math.min.
If you're interested how to do that in modern Javascript, it goes like this:
minEvenElement = Math.min.apply(Math, myArray.filter(function(e) { return !(e % 2) }))

Categories