【问题标题】:Filter Method Behavior过滤方法行为
【发布时间】: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


【解决方案1】:

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

让我们看看.. 在第一个代码中,过滤函数要么返回num,要么不返回任何内容(在negatives.push() 之后没有return,因此它隐式返回undefined)。

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

第二个版本返回 numnegatives.push()调用的返回值,这是by definition

返回值

调用方法的对象的新长度属性。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-07
    • 1970-01-01
    相关资源
    最近更新 更多