Javascript 过滤整数

Javascript Filter integers

我正在 FreecodeCamp 上学习 javascript。而且,我的问题的解决方案并没有帮助我更多。 我们必须过滤保存在 const 变量中的数组中的整数。

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
  "use strict";
const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
 return squaredIntegers;
};

const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);

这部分我真的看不懂num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );

为什么使用 parseint() 方法和 Math.pow。有人可以解释一下为什么吗?

谢谢。

parseInt(num)给出num的整数部分,例如parseInt(3.14) === 3 //true。 使用 num % parseInt(num) 基本上给出了数字与其整数部分之间的差异。如果不是 0,则该数字将被丢弃。 Math.pow(num) 给出一个平方数,返回给新的数组。不过,num * num 在这方面更快,不必包含模块和调用对象 属性.

除此之外,解决方案中的代码非常拥挤,我建议将其分解以提高可读性。似乎它的书写风格增加了混乱。

const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );
 return squaredIntegers;

此处在 filter 中,检查 num 是否为正数 (num>0) 并且 num 是否为 integer。用于检查整数。 num % parseInt(num) parseInt 将 num 更改为一个 integer,并且一个数字本身的 modulus 为 0,因此条件 num % parseInt(num)==0Math.pow(num,2) 用于对 num 进行平方。

很多人已经很好地解释了这一点。你也可以做这部分

const squaredIntegers = arr.filter( (num) => num > 0 && num % parseInt(num) === 0 ).map( (num) => Math.pow(num, 2) );

像这样,应该没有问题。希望这会有所帮助。

const squaredIntegers = arr.filter( (num) => num > 0 && num % 1 === 0 ).map( (num) => num * num );
const squaredIntegers = arr.filter(
    (num) => {
        if (Number.isInteger(num) && num >0){
        return num;
}}
).map((num) => num *num); // Math.pow(num, 2) can also be used here
return squaredIntegers;
};

尽管上述所有解决方案都可以正常工作,但对于您的问题来说,这可能是一个更简单的解决方案。 num*num 也可以替换为 Math.pow(num, 2).

试试这个,它不仅会过滤掉负数一次,而且 returns 只会过滤掉那些整数。

const squareList = arr => {
  let myArr = arr
        .filter(item => item > 0)
        .reduce((a, current) => a.concat(current*current) , [])
        .filter(num => Number.isInteger(num));
  return myArr;
};

const squaredIntegers = squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]);
console.log(squaredIntegers);// Prints : [16, 1764, 36] on console.

使用 reduce 语句的更简单方法是这样

const squareList = arr => {
  // Only change code below this line
  let myArr = arr.filter(user => Number.isInteger(user) && user > 0)
               .reduce((sqr,num) => sqr.concat(num*num), []);
  return myArr;
  // Only change code above this line
};

const squaredIntegers = squareList([-3, 4.8, 5, 3, -3.2]);
console.log(squaredIntegers);

其中 Number.isInteger() 用于过滤小数,user > 0 用于过滤 arr

中的负值