if statement wont trigger inside a for loop

Started by
5 comments, last by mercutio604 5 years, 1 month ago

var bestPrice = 0;
var bestLocation = "";

for(var p = 0; p < planets.length; p++){
    var demand = getBasePriceAndInfluence(itemKey, planets[p], "demand");
    var sellPrice = calcPrice(demand[0], demand[1], "demand");
    console.log("sell price: " + sellPrice);
    console.log("bestprice: " + bestPrice);
    if (sellPrice > bestPrice)
    {
    	bestPrice = sellPrice;
    	bestLocation = p;
    	console.log("switch for bestprice: " + bestPrice);
	}
}

sample log:

sell price: 505
bestprice: 0
switch for bestprice: 505
sell price: 1244
bestprice: 505
sell price: 1037
bestprice: 505
sell price: 1164
bestprice: 505
sell price: 1224
bestprice: 505
 
as you can see it goes through the first time and goes into the if statement but all others didn't go through it... ??? confused.
 
Anyone know why this is acting this way?
 
Advertisement
15 minutes ago, mercutio604 said:

var sellPrice = calcPrice(demand[0], demand[1], "demand");

Can it be the function returns the price as a string?

In this case the if statement could compare alphabetically and "5xx" is larger than all those "1xxx".

 

Because the string "505" is alphabetically ordered after "1164"; i.e. `"505" > "1164"`.  Double check the types of your variables.  You can assert that the operands are number-like by using the unary plus operator:

 


console.log(
	'p=', p,
	'demand=',    typeof demand,    demand,
	'sellPrice=', typeof sellPrice, sellPrice
);

if ( +sellPrice > +bestPrice ) {
	bestPrice = sellPrice;
	bestLocation = p;
	console.log("switch for bestprice: " + bestPrice);
}

 

you guys were right i tried parsing int and it works now

 

thanks

Welcome to Javascript!

the sad part was, I was using toString() in the function return statement because the other calls on it need it as a string.

So technically it was my fault :(

But I didn't know you could compare strings with a > and it would work. I would expect an error of some kind.

So I was looking at a completely different direction as the problem.

 

Well learned something new.

 

Edit: Scratch that I didnt even need it as a string >.<!
I can leave it as a number for everything

This topic is closed to new replies.

Advertisement