简体   繁体   English

我不得不使用 filter() 方法重构 function,但我失败了

[英]I had to refactor a function using the filter() method, but I failed

The original code of the function was: function的原码是:

getGreaterThan: function(input) {
  let greaterValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  let greaterNums = [];
  for (let j = 0; j < greaterValues.length; j++) {
    if (greaterValues[j] > parseInt(input)) {
      greaterNums.push(greaterValues[j]);
    }
  }
  return greaterNums;
}

This is my implementation:这是我的实现:

return [parseInt(input).filter((greaterNum) => input < greaterNum)];]

How can I proceed with this?我该如何继续呢?

You should be filtering greaterValues , not parseInt(input) .您应该过滤greaterValues ,而不是parseInt(input)

There's no need to put [] around the return value.没有必要将[]放在返回值周围。 filter() returns an array by itself. filter()本身返回一个数组。

getGreaterThan: function(input) {
  const greaterValues = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
  input = parseInt(input); // no need to do this each time through the loop
  return greaterValues.filter(val => val > input);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM