for (var i=0;i<5;++i){
alert(i);
}
for (var i=0;i<5;i++){
alert(i);
}
These two constructs return the same result: 0,1,2,3,4. Why? What are the differences between them? Does it matter what increment i use in for loop?
If you put ++ in front of the variable you increment the value before returning it (in that statement), if you put it behind you return the value, then increment it afterwards. Since you are doing nothing with the value in the statement the result after said statement is the same.
Consider this:
var i = 0;
var a = ++i; // a is 1
var b = i++; // b is also 1, i is now 2.
The former is a pre-increment, the latter a post-increment.
The difference is nothing your example as you're not assigning the result to anything, but show themselves quite alot when assigning the result to another variable.
var i = 0;
alert(i); // alerts "0"
var j = i++;
alert(j); // alerts "0" but i = 1
var k = ++i;
alert(k); // alerts "2" and i = 2
Live example: http://jsfiddle.net/ggUGX/
for a loop you dont see any difference, but the ++i increments and then returns the value wheras i++ returns a value and then increments. If you have code like
var a = myarray[++i]
and
var a = mayarray[i++];
they will return differnet values
These two code blocks should have the same output. The difference between i++ and ++i is the order in which the variable i is incremented and is only important when using the value of i at the same time.
For instance, ++i and i++ do effectively the same thing unless you're using it like so:
y = i++;
or
y = ++i;
In the first example i is incremented AFTER y is set to its value (so if i = 0, y = 0, then i = 1). In the second example i is incremented BEFORE y is set to its value (so if i = 0, i = 1, y = 1).
Because you do not use i++ in a similar fashion in a for statement, it has no effective difference.
i++ or ++i in the for loop executes as a different statements. So, putting i++ or ++i in for loop doesn't make any difference.
Related
I am trying to achieve 3,4,5 in output. But, am getting only 3,5 .its jumping/skipping one number. Donno why. Given my code below. Help me to fix the error and please let me know why its happening and what i am doing as error ?
Expected output,
3
4
5
output am getting,
3
5
my code,
var input1, input2;
input1 = Number(2);
input2 = Number(5);
for(let i=input1;i<input2;i++) {
i=i+1;
console.log(i);
}
The for loop already increments i for you. The loop you wrote executes in the following path, going from 1 -> 2 -> 3 -> 4 -> 2 -> 3 and repeats unless the check at 3 is false:
for(
let i=input1; // 1. Declare initial value [i]
i<input2; // 3. Check if [i] < [input2]
i++ // 4. increment [i] by 1
)
{
i=i+1; // 2. Run the contents of the loop body
console.log(i);
}
That means
// First iteration
i = input1 // 1. i = Number(2);
i = i + 1; // 2. i = 2 + 1;
console.log(i) // 2. console.log(3);
i < input2 ? // 3. Check if i is smaller than input2. End loop if not
i++; // 4. Increment i so i = 4
// Second iteration
i = i + 1; // 2. i = 4 + 1;
console.log(i) // 2. console.log(5);
i < input2 ? // 3. Check if i is smaller than input2. End loop if not
// End loop since i < input2 is not true
You are incrementing i inside the body of the for loop even though it already does it for you.
input1 should also be 3.
Use:
var input1, input2;
input1 = Number(3);
input2 = Number(5);
for (let i = input1; i <= input2; i++) {
console.log(i);
}
You are incrementing variable 'i' two times
On for loop
for(let i=input1;i<input2;i++) {}
Inside for loop
i=i+1;
So your variable 'i' will increment with 2
I want to use function with while to print only 10 numbers starting from the number I choose.
But while loop doesn't stop looping.
id = prompt('Write any number.');
function numbering(a) {
var i = a;
var j = a + 10;
while (i < j) {
document.write(i);
i++;
}
};
numbering(id);
Try this:
var id = parseInt(prompt('Write any number.'), 10);
In your example id will be of type string and the comparisons won't work as you expect.
When you use function numbering(a) {, the variable a is passed as string.
This results in i and j being set as string.
Taking example:
Suppose you pass 2 as input, your variables will be set as a="2", i="2" and j="210". So according to your condition, it'll print starting from 2 till 209.
You can change your code to parse a as number to achieve your result; something like:
function numbering(a) {
a = parseInt(a); //parse as Int here
var i=a; var j=a+10;
while (i < j)
{
document.write(i);
i++;
}
};
Try it with a for-loop:
for(var i=0; i<10; i++){ doSomething}
You can try with this for-loop function :
id=prompt('Write any number.');
function numbering(a) {
for (let i = a; i < a + 10; i++){
document.write(i);
}
};
numbering(id);
You can add a parseInt(id) to you numbering function parameter call if you want to parse the input into a number
When you enter a number in the prompt, it is supplied as a string. Since you have not converted this into a number, the line var j = a + 10 is actually joining the two values as if they were strings.
For example, if you enter "5" into the prompt, then var j = "5" + 10 returns "510". Only when you then compare the two variables in the while loop with i < j does it get interpreted as a number, and will loop from 5 to 510.
The easiest way to convert a string into a number is to use parseInt(value).
The prompt function returns a string.
The problem is that you are concatenating a string with the number 10.
If you write your variables to document, you can see the problem:
id=prompt('Write any number.');
function numbering(a) {
var i=a; var j=a+10;
document.write(i);
document.write("<br/>");
document.write(j);
document.write("<br/>");
//while (i < j){
// document.write(i);
// i++;
//}
};
numbering(id);
This will fix your problem:
var id=parseInt(prompt('Write any number.'));
you need the parseInt function because what you getting from promt is string. For example 5 +10 . For javascript , it will be 510 .
id=prompt('Write any number.');
function numbering(a) {
var i=parseInt(a); var j=parseInt(a)+10;
while (i < j){
document.write(i);i++;
}};
numbering(id);
document.write(i +"<br>");
In console i am getting proper result. just add line break to see whole result in viewport
I've written a function that takes plevel (integer) and slevel (array of strings of numbers) and finds the smallest difference between plevel and a value in slevel. However, when I run the script, it is unresponsive and the debugger says that diff is undefined.
var findDiff = function findDiff(plevel, slevel) {
var diff = new Array();
for (i=0; i<=slevel.length; i++) {
sleveli = parseInt(slevel[i]);
diff.push(Math.abs(plevel-sleveli));
}
if (diff.length > 1){
diff.sort(function(a, b){return a-b});
return diff[0]
}
else{
return diff[0];
}
}
The function is invoked here:
var matches = new Array();
var newFetch = Data.find().fetch();
for(i = 0; i <= newFetch.length; i++ ){
pointsMatch = 0
var difference = findDiff(newFetch[i].level, spec.level);
pointsMatch -= (difference*3);
matches.push([newFetch[i], pointsMatch])
}
console.log(matches)
Data is a mongoDB collection. spec.level is an array of strings of numbers stored as a property in an object.
I would like to point out name space pollution, which may cause serious troubles. In my understanding, you have two cases of namespace pollution, one of it creates an endless loop.
You have actually an inner an outer loop, separated by a function. Your outer for loop:
for(i = 0; i <= newFetch.length; i++ ){
pointsMatch = 0
...
And then your inner for loop:
for (i=0; i<=slevel.length; i++) {
sleveli = parseInt(slevel[i]);
...
Because of the missing var before i, both for loop definitions are actually like this:
for (window.i=0; ...
So the inner loop overwrites the variable i the outer loop depends on to terminate. i is "polluting" namespace.
The second case is harmless:
sleveli = parseInt(slevel[i]);
Because of the missing var, this results in fact in
window.sleveli = parseInt(slevel[i]);
Better would be
var sleveli = parseInt(slevel[i]);
But this is a time bomb.
I suggest you add var to the definitions of i in the for loop.
I think the people in the comments are right; we need to see some more of your input to debug this properly. But you can simplify your code a lot by tracking the mins as you go:
var findDiff = function findDiff(plevel, slevel) {
var min = Number.MAX_SAFE_INTEGER;
for (i=0; i<slevel.length; i++) {
sleveli = parseInt(slevel[i]);
var diff = Math.abs(plevel-sleveli);
min = Math.min(min, diff)
}
return min;
}
var a = ["1", "2", "10", "17"]
var p = 6
// We're expecting 4 as the min diff
console.log(findDiff(p, a))
// ...prints out 4 :-)
http://repl.it/ceX
As Omri points out, use < not <= in your for loop.
Note - Number is not always available -- see here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number/MAX_SAFE_INTEGER
You could alternatively set the initial min to something suitably large for your likely data, like 2^10
I have two arrays set up that I wish to multiply each value within each together. Then I want to get the total value in the form of a variable. I will post what I have below. I think my problem may be that I am not sure how to get each run of the code to add together?
var flatQty=[];
flatQty[0]= document.getElementById("flats1").value;
flatQty[1]= document.getElementById("flats2").value;
flatQty[2]= document.getElementById("flats3").value;
flatQty[3]= document.getElementById("flats4").value;
flatQty[4]= document.getElementById("flats5").value;
var flatWidth=[];
flatWidth[0]=document.getElementById("flatwidth1").value;
flatWidth[1]=document.getElementById("flatwidth2").value;
flatWidth[2]=document.getElementById("flatwidth3").value;
flatWidth[3]=document.getElementById("flatwidth4").value;
flatWidth[4]=document.getElementById("flatwidth5").value;
for (var i=0;i<5;i++)
{
var flatCharge=flatWidth[i]*2*flatQty[i];
}
document.getElementById("flatTest").innerHTML=flatCharge;
When I run the code nothing is printed into the id="flatTest".
Your problems is that you are redefining your flatCharge inside the loop, therefore it's not correct outside the loop. In addition, you are not adding the values, but replacing them on every iteration of the loop. Change the loop to this:
var flatCharge = 0;
for (var i = 0; i < 5; i++) {
flatCharge += flatWidth[i] * 2 * flatQty[i];
};
document.getElementById("flatTest").innerHTML = "" + flatCharge;
and it should work.
.value properties are strings, not numbers. so you should be careful how you handle them. Multiplication actually works for strings, but not for addition where the + operator performs concatenation instead.
There are numerous methods of converting from string to number:
+s - will convert the expression s into a number
parseFloat(s)
parseInt(s, 10) for whole numbers
The actual problem in your code is that you're overwriting the calculated value in each pass using the = operator instead of +=.
I suggest refactoring your entire code thus to avoid all of the repetition:
var flatCharge = 0;
for (var i = 1; i <= 5; ++i) {
var qty = +document.getElementById('flats' + i).value;
var width = +document.getElementById('flatwidth' + i).value;
if (!isNaN(qty) && !isNaN(width)) {
flatCharge += 2 * qty * width;
}
}
I was for quite some time under the impression that a for loop could exist solely in the following format:
for (INITIALIZER; STOP CONDITION; INC(DEC)REMENTER)
{
CODE
}
This is, however, most definitely not the case; take a look at this JavaScript implementation of the Fisher-Yates Shuffle:
shuffle = function(o)
{
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
This little snippet completely blows my mind; how in the world is so much going on inside a simple for loop declaration? I mean... it doesn't even open a brace! All of the magic is being done right there inside the for statement. It'd be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does. Much appreciated in advance.
shuffle = function(o){
for (
var j, // declare j
x, // declare x
i = o.length; // declare i and set to o.length
i; // loop while i evaluates true
j = parseInt(Math.random() * i), // j=random number up to i
x = o[--i], // decrement i, and look up this index of o
o[i] = o[j], // copy the jth value into the ith position
o[j] = x // complete the swap by putting the old o[i] into jth position
);
return o;
};
This is starting with i equal to the number of positions, and each time swapping the cards i and j, where j is some random number up to i each time, as per the algorithm.
It could be more simply written without the confusing comma-set, true.
By the way, this is not the only kind of for loop in javascript. There is also:
for(var key in arr) {
value = arr[key]);
}
But be careful because this will also loop through the properties of an object, including if you pass in an Array object.
The generalized format of a for loop (not a for-in loop) is
for ( EXPRESSION_1 ; EXPRESSION_2 ; EXPRESSION_3 ) STATEMENT
The first EXPRESSION_1 is usually used to initialize the loop variable, EXPRESSION_2 is the looping condition, and EXPRESSION_3 is usually an increment or decrement operation, but there are no rules that say they have to behave like that. It's equivalent to the following while loop:
EXPRESSION_1;
while (EXPRESSION_2) {
STATEMENT
EXPRESSION_3;
}
The commas are just an operator that combines two expressions into a single expression, whose value is the second sub-expression. They are used in the for loop because each part (separated by semicolons) needs to be a single expression, not multiple statements. There's really no reason (except maybe to save some space in the file) to write a for loop like that since this is equivalent:
shuffle = function(o) {
var j, x;
for (var i = o.length; i > 0; i--) {
j = parseInt(Math.random() * i);
x = o[i - 1];
o[i - 1] = o[j];
o[j] = x;
}
return o;
};
INITIALIZER can declare and initialize multiple variables. STOP CONDITION is a single test (here it's just "i"), and INCREMENTER is an expression to be executed each time after body (the comma operator lets you have multiple sub-expressions, which all get executed. ). The body of the for loop is just the empty statement ";"
The code you quote is obfuscated in my opinion. There are much clearer ways to write the same functionality.
However, your understanding is pretty much right. The following is the exact same code, except for whitespace and comments.
for (
// Initializer
var j, x, i = o.length;
// Continue condition
i;
// Operation to be carried out on each loop
j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x
)
// empty body, equivalent to { }
;
It's much clearer to write the equivalent:
var j,x,i = o.length;
while(i) {
j = parseInt(Math.random() * i);
x = o[--i];
o[i] = o[j];
o[j] = x;
}
There are other optimisations that could be made for readability - including using while(i > 0) instead of while(i), and splitting out the --i into an i-- on a separate line.
There's really no reason for for() to exist, except for readability. These two are equivalent:
{ // this block is to scope int i
int i=0;
while(i<100) {
myfunc(i);
i++;
}
}
for(int i=0; i<100; i++) {
myfunc(i);
}
You should use whichever is most readable for a given time. I'd argue that the author of your code has done the opposite. In fairness, he may have done this in order to achieve a smaller JS file for faster loading (this is the kind of transform an automated code compactor could do).
Syntax of for loop is:
for (pre-block; condition; post-loop-block)
loop-block;
First, pre-block is executed, various variables are defined.
In each loop:
check condition
execute loop-block
execute post-loop-block
repeat from 1.
That statement does comply with your initial format.
It turns out you could add more than one sentence of each using "," ( comma )
So:
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
Could be analyzed like this:
for (var j, //INITIALIZER(s)
x,
i = o.length;
i; // STOP CONDITION ( i )
j = parseInt(Math.random() * i), // INC(DEC)REMENTER
x = o[--i],
o[i] = o[j],
o[j] = x); // CODE ( ; )
As you see, it fits completely in your initial format.
They've pretty much just moved the body of the loop into the incrementer section. You can re-write the for loop as a while loop to get some idea of what it is doing:
shuffle=function(o) {
var j; //Random position from 0 up to the current position - 1
var x; //temp holder for swapping positions
var i=o.length; //current position
while(i>0) { // Loop through the array
j = parseInt(Math.random()*i); //get a lower position
x = o[--i]; // decrement the position and store that position's value in the temp var
o[i]=o[j]; // copy position j to position i
o[j]=x; // copy the temp value that stored the old value at position i into position j
}
return o;
}
The first three var's are the initialzier expanded out, the check in the while is the stop condition and the body of the while is what was done in the incrementer portion of the for.
Edit: Corrected per Gumbo's comment
this goes all the way back to C syntax - from which javascript has stole a bunch. the main trick is the comma-operator which seems to appear in almost no other place except for loops
The first clause initializes any variables you want to use. The second clause is indeed the stop condition. The third clause includes any logic to be executed at the end of each iteration. Multiple statements can be separated by commas.