我编写了一个函数,该函数仅计算数组realNumberArray中的正整数的平方,并返回带有结果的新数组。
示例: [4,5.6,-9.8,3.14,42,6,8.34,-2] 返回[16,1764,36]
您将如何仅使用reduce()重新创建以下函数,什么是首选方式?
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
const squaredIntegers = arr;
let newArr=squaredIntegers.filter(val=>val%1==0 && val>0).map(val=>Math.pow(val,2))
return newArr;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
答案 0 :(得分:0)
仅在测试通过时推入累加器:
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = arr => arr.reduce((a, val) => {
if (val % 1 == 0 && val > 0) {
a.push(val ** 2);
}
return a;
}, []);
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
答案 1 :(得分:0)
您可以通过以下方式实现此目标:
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const result = realNumberArray.reduce((a, i) => Number.isInteger(i) && i > 0 ? a.concat([ i ** 2 ]) : a, [])
console.log(result)
为解决这个问题,上面的代码将输入数组realNumberArray
缩小为result
数组,每次减少迭代次数:
Number.isInteger(number)
的整数,则将对其进行“过滤”。如果数字i
是整数,则代码为a
将该数字的“平方”连接到输出数组a.concat([ i ** 2 ])
(请注意,number ** 2
是Math(number, 2)
的简写i
不是整数,则通过直接返回该迭代的当前输出数组a
来过滤掉它希望有帮助!
答案 2 :(得分:0)
使用减少
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
const squaredIntegers = arr;
let newArr = squaredIntegers.reduce((acc, val) => {
if (val % 1 == 0 && val > 0) {
acc.push(Math.pow(val, 2));
return acc;
}
return acc
}, [])
return newArr;
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
答案 3 :(得分:0)
最好的方法是检查该数字上的parseFloat()
和parseInt()
是否相同,以查明给定的数字是纯整数。然后,根据数字应大于0的附加条件,在if
中添加附加条件。
var arr = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2] ;
var res = arr.reduce((acc, num) => {
if(num > 0 && parseFloat(num) === parseInt(num)){
acc.push(num*num);
}
return acc;
}, []);
console.log(res);
答案 4 :(得分:0)
您可以连接一个空值平方的数组,具体取决于非整数值或负数。
const
realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2],
squareList = array => array.reduce((r, v) => r.concat(v % 1 || v < 0 ? [] : v * v), []),
squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
答案 5 :(得分:0)
尝试一下
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const squareList = (arr) => {
return arr.reduce((a,val)=>{
if(val%1==0 && val>0)
a.push(Math.pow(val,2))
return a;
},[])
};
const squaredIntegers = squareList(realNumberArray);
console.log(squaredIntegers);
答案 6 :(得分:0)
使用reduce和Array解构代替push方法
const realNumberArray = [4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2];
const newArray = realNumberArray.reduce((acc, curr) => (curr % 1 === 0 && curr >= 0 ? [...acc, curr * curr] : acc), []);
console.log(newArray);
答案 7 :(得分:0)
您可以使用reduce这样操作:
const squareList = arr =>
arr.reduce((out, x) => x % 1 === 0 && x > 0 ? [...out, x * x] : out, []);
console.log(squareList([4, 5.6, -9.8, 3.14, 42, 6, 8.34, -2]));