Javascript比较数字是行不通的 [英] Javascript comparing numbers isn't working
问题描述
我正尝试正常化数据,并意识到它不工作,因为我得到不正确的最大值。但是,数字的比较是不正确的。这是我的代码:
var max = Number.MIN_VALUE;
var min = Number.MAX_VALUE;
for(i = 0; i< array.length; i ++)
{
if(array [i]> max)
{
max = array [一世]; (i = 0; i< array.length; i ++)
{
}
if(array [i] min)
{
min = array [i];
}
}
console.log(max:+ max);
console.log(min:+ min);
(i = 0; i< array.length; i ++)
{
if(array [i]!= 0)
{$ b $如果(array [i]> max)
{
console.log(i +:+ array [i] +yes);
}
else
{
console.log(i +:+ array [i] +no+ max);
$ b $ / code $ / pre>
我是得到很多控制台输出,但是这里有一个例子:
pre $ code> 241590:17.5799 no 9.86874
这意味着由于某种原因,JS认为17.5799不大于9.86874。为什么会发生这种情况,我该如何解决这个问题?谢谢!
编辑1:打印数组[i] - max时,我得到了正确的区别...除了是负数。 $ b
这是因为你的数组包含字符串,而不是数字。
so'9.95799' > '89 .86874'=> true :)
改为使用数字
I am trying to normalize data and realized that it's not working because I am getting the incorrect maximum. However, the comparing of numbers isn't working correctly. Here is my code:
var max = Number.MIN_VALUE;
var min = Number.MAX_VALUE;
for (i = 0; i < array.length; i++)
{
if(array[i]>max)
{
max = array[i];
}
}
for (i = 0; i < array.length; i++)
{
if(array[i]<min)
{
min = array[i];
}
}
console.log("max: " + max);
console.log("min: " + min);
for (i = 0; i < array.length; i++)
{
if(array[i]!=0)
{
if(array[i]>max)
{
console.log(i+": " + array[i] + " yes");
}
else
{
console.log(i+": " + array[i] + " no " + max);
}
}
}
I am getting a lot of console output, but here is one example:
241590: 17.5799 no 9.86874
meaning that for some reason, JS thinks that 17.5799 is not bigger than 9.86874. Why is this happening and what can I do to fix it? Thank you!
EDIT 1: When printing array[i] - max, I end up with the correct difference...except it's negative.
It's because you'r array contains strings, not numbers.
so '9.95799' > '89.86874' => true :) Use numbers instead
这篇关于Javascript比较数字是行不通的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!