js将元素与零比较返回错误结果

时间:2017-10-19 20:29:34

标签: javascript

我有一个浮动列表,想要检查它们是否都是负数。

当我遍历我的列表:el = [0.0,0.0,0.0,0.0,-34.470000000000006]时,我得到了,但它应该是假的。

var weekly_plus_perfs = true;

for (var el = 0; el < weekly_plus.length; el++) {
    if (weekly_plus[el]>0) {
        weekly_plus_perfs = false;
    }
}

我在哪里错过了什么?

5 个答案:

答案 0 :(得分:0)

您应该将测试更改为>=

这些数字都不超过零。原始条件为TRUE,仍为。

答案 1 :(得分:0)

您可以查看>=并在找到错误值时退出。

&#13;
&#13;
var weekly_plus = [0.0, 0.0, 0.0, 0.0, -34.470000000000006],
    weekly_plus_perfs = true,

for (var el = 0; el < weekly_plus.length; el++) {
    if (weekly_plus[el] >= 0) {
        weekly_plus_perfs = false;
        break;
    }
}

console.log(weekly_plus_perfs);
&#13;
&#13;
&#13;

ES5与Array#every

&#13;
&#13;
var weekly_plus = [0.0, 0.0, 0.0, 0.0, -34.470000000000006],
    weekly_plus_perfs = weekly_plus.every(function (v) {
        return v < 0;
    });

console.log(weekly_plus_perfs);
&#13;
&#13;
&#13;

ES6

&#13;
&#13;
var weekly_plus = [0.0, 0.0, 0.0, 0.0, -34.470000000000006],
    weekly_plus_perfs = weekly_plus.every(v => v < 0);

console.log(weekly_plus_perfs);
&#13;
&#13;
&#13;

答案 2 :(得分:0)

数组还有一个every函数,用于评估列表中所有元素的条件是否为真。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every

var el = [0,1,0,-13]; 
var el2 = [1,2,3,4];
console.log( el.every((e)=>{return e >= 0;}) ); 
console.log( el2.every((e)=>{return e >= 0;}) ); 

答案 3 :(得分:0)

0不是否定的,所以测试应该更好地理解为:

var weekly_plus_perfs = false;
for(var el=0; el<weekly_plus.length;el++){
  if(weekly_plus[el] < 0){
    weekly_plus_perfs = true;
 }}

但是, Array.every() 方法更适合此问题:

console.log([-12, -5, 0, -5, 44].every(function (element, index, array) { 
  return element < 0; 
}));   // false 


console.log([-12, -54, -18, -130, -44].every(function (element, index, array) { 
  return element < 0; 
})); // true

答案 4 :(得分:0)

使用Array.every()isNaN()函数:

&#13;
&#13;
var list = [0.0, 0.0, 0.0, 0.0, -34.470000000000006];
    all_negative = list.every(function(n) { return !isNaN(n) && n < 0; });
	
console.log(all_negative);
&#13;
&#13;
&#13;