过滤方法行为



为什么过滤方法不能使用三元条件,因为它可以使用if条件?

如果它适用于if..else

let numbers = [-1, -2, -3, 1, 2, 3];
let negatives = [];
let positives = numbers.filter(num => {
if(num > 0) {
return num;                      // positives array => [1, 2, 3]
} else {
negatives.push(num);             // negatives array => [-1, -2, -3]
}
})

如果它适用于?

let positives = numbers.filter(num => num > 0 ? num : negatives.push(num));
// positives array => [-1, -2, -3, 1, 2, 3]
// negatives array => [-1, -2, -3]

我尝试使用if条件过滤方法,它返回我期望的结果。但是我不期望的结果是,当它与三元条件一起工作时。

问题是你误解了你粘贴的代码的作用。

看看. .在第一段代码中,过滤函数要么返回num,要么不返回(negatives.push()之后没有return,因此隐式返回undefined)。

function fn(){ 
// no explicit return
}
const what = fn();
typeof what === "undefined"; // true

第二个版本,返回numnegatives.push()调用的返回值,根据定义:

返回值调用该方法的对象的新长度属性。

因此,在代码的第二个版本中,filter接收每个数字:0,1,2…等等......第一次出现将被视为"错误"。(0是一个"错误";值),因此它将从结果数组中过滤掉,下面的负数将包含在结果数组中,因为过滤函数将返回" true "它们的值(正数是"真值");

话虽如此…

filter函数用于过滤事物以外的其他任务是一种不好的做法。在这种情况下,你需要区分阳性和阴性,使用forEach,这是更清晰和适当的。

const positives = [];
const negatives = [];
numbers.forEach(num => {
if(num > 0) { // Note: that this comparison will send ZEROES to negatives array, which could lead to a bug.
positives.push(num);
} else {
negatives.push(num);
}
}); 

或简单的:

const positives = [];
const negatives = [];
numbers.forEach(num => (num > 0 ? positives : negatives).push(num));

数组方法filter期望一个返回布尔值的回调。在第二个例子中,当num为正(这是真)时,您返回num

但是,当num为负时,该方法返回的negatives.push(num)的结果也为真。

最新更新