正整數平方陣列 JavaScript
假設我們有一個包含一些數字的陣列,正數、負數、小數和整數。我們必須編寫一個函式,這個函式接收一個數組,並返回原始陣列中所有正整數的平方陣列。
讓我們編寫這個函式的程式碼 −
示例
const arr = [1, -4, 6.1, 0.1, 2.6, 5, -2, 1.9, 6, 8.75, -7, 5];
const squareSum = (arr) => {
return arr.reduce((acc, val) => {
//first condition checks for positivity and second for wholeness of the number
if(val > 0 && val % 1 === 0){
acc += val*val;
};
return acc;
},0);
}
console.log(squareSum(arr));輸出
控制檯中的輸出將是 −
87
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP