Why doesn't this for loop read this in passed argument properly? - javascript

Below is my code
function generateGrid(spacing, boundBox, geometry) {
console.log(spacing);
console.log(boundBox);
var grid = [];
console.log(spacing);
for (var x = boundBox[0]; x < boundBox[2]; x = x + spacing) {
for (var y = boundBox[1]; y < boundBox[3]; y = y + spacing) {
if(geometry.intersectsCoordinate([x, y])) grid.push([x, y]);
console.log(boundBox[3] - y)
}
console.log(boundBox[1] - x)
}
console.log(grid);
}
If spacing is replaced by a number like 10000 the for loop executes fine.

From your Console screenshot it looks like the passed in argument is the string "10000" rather than the number 10000.
Either check the code that's calling your function, or convert to an integer inside the function, for example by using parseInt(spacing).
As a tip to help with spotting any similar issues in the future, Chrome's console.log shows numeric values in blue and string values in black.

x is a number so use String(x) so you use operator + between two strings, that would give you "15" + "1" = "151", but that is probably not what you wanted

Related

Operator precedence ' ++ ' JavaScript [duplicate]

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.

Why does it only sums the last two numbers?

I am trying to make a program that sums every number given as parameter. To do so, I wrote the following code:
var x = 0;
var i = 2;
while (isNaN(+process.argv[i + 1]) == false){
x = +process.argv[i] + +process.argv[i + 1];
i++;
}
console.log(x);
The problem is that the code I wrote sums only the 2 last parameter.
I launch my code using node sumArgs.js 1 2 3
and it returns 5.
What is the problem with my code and why isn't it working as planned ?
What is happening every time you loop through, it is taking the current parameter, and the next, and setting x to equal the sum of those.
x needs to be added to, not set. You can do this either:
x += process.argv[i]
or
x = x + process.argv[i]
I'm also not sure why you are adding 2 arguments each loop, as this will cause the sum to be incorrect at the end (unless you increment i twice each loop).
I should note that map reducing it, as in another comment, wouldn't work as the first 2 arguments would not be parameters passed to the program, they would be "node" and "program.js".
var x = 0;
var i = 2;
while (isNaN(+process.argv[i]) == false){
x = x + process.argv[i];
i++;
}
console.log(x);
However, what you could do is use slice:
var sum = process.argv.slice(2).reduce(function(previousValue, currentValue) {
return previousValue + currentValue;
});

Combinations Of Numbers To Equal One Total

In javascript I get two numbers let's call them x & y and an array of integers with random int's from 0 - 10 arrayints.
x is the number I'm trying to get by combining y with any of the numbers in arrayints.
for example: lets say x = 8 and y = 3 and arrayints consists of numbers arrayints(1,7,2,7,4,5)
so x could equal = y + 5
or
x = y + 1 + 4
All the values in x, y and arrayints will be random and always <= 10.
Please advise if more information is needed and everything will be in javascript or jquery no fuss as far as my code goes I will copy and paste but it will just be one blob of incromprehensible letters which are giving me an headache.
function makex(x,y) {
//this is how I get the array of random ints <=10
$("#div").children().each(function(n, i) {
var id = parseInt(this.id+"");
});
}
Here's a recursive solution that returns an array of the integers that add up to x, including y (or an empty array if it doesn't exist). If you want to exclude y, then feel free to make a wrapper for this.
function make(x, y, intOptions) {
var z = x - y
if (intOptions.indexOf(z) !== -1) {
return [y, z];
} else if (intOptions.length > 1){
var i = intOptions.length;
var ans;
while (i--) {
ans = make(z, intOptions[i], intOptions.slice(0, i))
if (ans.length) {
return [y].concat(ans);
}
}
}
return [];
}

Javascript increment while assigning

I was having a conversation about the prefix increment operator, and we seem to have run into a disagreement.
When running this code:
var x = 0;
x = ++x;
is the second line equivalent to:
x = (x = x + 1) OR
x = (x + 1)
It is hard to tell the difference because the results are identical (both result in x having a value of 1)
I believe that the value is not saved to the original variable when the left hand side of the assignment is the variable itself.
My counterpart disagrees and thinks the value is saved to the original variable whenever the ++ operator is used.
Which one of us is right?
It is saved, so it is similar to the first example.
Take for example this code:
var v = 0;
v = ++v + ++v + ++v;
// Returns 6
That is because this will translate to:
v = (0+1) + ((0+1)+1) + (((0+1)+1)+1);
Or, to be more accurate:
v = 0+1 +
v = 1+1 + //Previous value of v + 1
v = 2+1 //Previous value of v + 1
Why?
++v will first save the incremented value of v, then it will return this incremented value.
To simplify things, try this in your console:
x = 0;
++x;
If ++x would resolve to x + 1, the value of x would now still be 0, right?
Nope, your x will be 1. This means that ++x must have a assignment operator in there.
Just try writing both ++x and x++ out in full English sentences:
++x: increment x by one and return the value
x++: return the value of x, and increment it.
Your second line (x = ++x;) is equivalent to x = (x += 1), yes.Just look at any loop you've ever written:
for (var i = 0;i<100;i++)//<-- no need for another assign here
So you could've written ++x; all the same, but since that expression is the entire statement, it makes no difference if you write x++; or ++x...
As you probably know xxsomeVar increments the variable by 1, assigns the resulting value to that variable and then returns it, someVar++ returns the current value of the variable, and then increments it by 1 (the new value is assigned to the variable, too, of course).
So ++x; is the equivalent of x = (x + 1);
From the Language specs:
++prefix increment operator
Postfix++ increment operator
Doing:
var x = 0;
console.log(++x); // will make print 1
Doing :
var x = 0;
console.log(x++); // will make print 0
console.log(x); // will print 1
After reading the ECMAScript Language Specification in answer to the question it appears that ++x is equivalent to x = ( x = x + 1 ).
Translation of the steps outlined by the specification is:
The result of the operation will be assigned to x
Throw error if certain conditions are true
oldValue = x
newValue = oldValue + 1
assign newValue to x
return newValue
For the post-increment operator the above will return the oldValue instead of the newValue.
var x = 0;
// x is assigned 1 during the post-increment operation but because
// the oldValue is returned it is immediately replaced by 0.
x = x++;
console.log( x ) // prints 0

++someVariable vs. someVariable++ in JavaScript

In JavaScript you can use ++ operator before (pre-increment) or after the variable name (post-increment). What, if any, are the differences between these ways of incrementing a variable?
Same as in other languages:
++x (pre-increment) means "increment the variable; the value of the expression is the final value"
x++ (post-increment) means "remember the original value, then increment the variable; the value of the expression is the original value"
Now when used as a standalone statement, they mean the same thing:
x++;
++x;
The difference comes when you use the value of the expression elsewhere. For example:
x = 0;
y = array[x++]; // This will get array[0]
x = 0;
y = array[++x]; // This will get array[1]
++x increments the value, then evaluates and stores it.
x++ evaluates the value, then increments and stores it.
var n = 0, m = 0;
alert(n++); /* Shows 0, then stores n = 1 */
alert(++m); /* Shows 1, then stores m = 1 */
Note that there are slight performance benefits to using ++x where possible, because you read the variable, modify it, then evaluate and store it. Versus the x++ operator where you read the value, evaluate it, modify it, then store it.
As I understand them if you use them standalone they do the same thing. If you try to output the result of them as an expression then they may differ. Try alert(i++) as compared to alert(++i) to see the difference. i++ evaluates to i before the addition and ++i does the addition before evaluating.
See http://jsfiddle.net/xaDC4/ for an example.
I've an explanation of understanding post-increment and pre-increment. So I'm putting it here.
Lets assign 0 to x
let x = 0;
Lets start with post-increment
console.log(x++); // Outputs 0
Why?
Lets break the x++ expression down
x = x;
x = x + 1;
First statement returns the value of x which is 0
And later when you use x variable anywhere, then the second statement is executed
Second statement returns the value of this x + 1 expression which is (0 + 1) = 1
Keep in mind the value of x at this state which is 1
Now lets start with pre-increment
console.log(++x); // Outputs 2
Why?
Lets break the ++x expression down
x = x + 1;
x = x;
First statement returns the value of this x + 1 expression which is (1 + 1) = 2
Second statement returns the value of x which is 2 so x = 2 thus it returns 2
Hope this would help you understand what post-increment and pre-increment are!
var a = 1;
var b = ++a;
alert('a:' + a + ';b:' + b); //a:2;b:2
var c = 1;
var d = c++;
alert('c:' + c + ';d:' + d); //c:2;d:1
jsfiddle
var x = 0, y = 0;
//post-increment: i++ returns value then adds one to it
console.log('x++ will log: ', x++); //0
console.log('x after x++ : ', x); //1
//pre-increment: adds one to the value, then returns it
console.log('++y will log: ', ++y); //1
console.log('y after ++y : ', y); //1
It is clearer and faster to use ++i if possible :
++i guarantees that you are using a value of i that will remains the same unless you change i
i++ allows to use a value of i which will change in the "near future", it is not desirable if possible
Of course, it's not really much faster, only a little.

Categories

Resources