【发布时间】:2023-01-12 01:52:22
【问题描述】:
为什么过滤方法不能像使用 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 条件的 filter 方法,它返回了我预期的结果。但是当它与三元条件一起使用时,结果对我来说不是预期的。
【问题讨论】:
-
filter返回项目或不返回项目。不可能有与项目价值不同的价值。
标签: javascript arrays if-statement filter ternary