我需要协助来解决这个JavaScript挑战

时间:2019-06-21 20:23:55

标签: javascript

在此挑战中,我必须使用箭头函数语法来计算realNumberArray数组中仅正整数(小数不是整数)的平方,并将新数组存储在平方Integers中。 https://learn.freecodecamp.org/javascript-algorithms-and-data-structures/es6/write-higher-order-arrow-functions

到目前为止,我的代码。

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

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

3 个答案:

答案 0 :(得分:2)

您可以采取三个步骤:

  • 仅过滤带有Number.isInteger的整数。
  • 仅过滤正值。
  • 映射平方值。

const isPositive = v => v > 0;

const squareList = (arr) => {    
  "use strict";    
  return realNumberArray
      .filter(Number.isInteger)
      .filter(isPositive)
      .map(v => v * v);
};    

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];    
const squaredIntegers = squareList(realNumberArray);    
console.log(squaredIntegers);

答案 1 :(得分:0)

函数parseInt()不检查数字是否为整数;如果适用,它将字符串转换为整数。

要检查数字是否为整数,可以使用Number.isInteger()

在下面的代码段中,我们将过滤掉非整数和负值,然后使用带有箭头功能的map()计算所有剩余元素的平方。

const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];    
const squareList = (arr) => {    
  "use strict";
  //removing decimals from the passed array
  arr = arr.filter((elem) => Number.isInteger(elem) && elem >= 0); 
  //computing the squares
  var squaredIntegers = arr.map((elem) => elem * elem);
  return squaredIntegers;    
};    

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

答案 2 :(得分:0)

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;
    };

// test your code
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers)