php,api,gemini,json,random,astrology,data
Description
This function calculates the sum of all numbers within a JavaScript array. It handles empty arrays gracefully and non-numeric elements.
Code Snippet
function sumArray(arr) {
if (!arr || arr.length === 0) {
return 0;
}
let sum = 0;
for (let i = 0; i < arr.length; i++) {
if (typeof arr[i] === 'number') {
sum += arr[i];
}
}
return sum;
}
// Example usage:
const numbers = [1, 2, 3, 4, 5];
const sum = sumArray(numbers);
console.log("Sum of array:", sum); // Output: Sum of array: 15
const mixedArray = [1, 2, 'a', 4, 5];
const mixedSum = sumArray(mixedArray);
console.log("Sum of mixed array:", mixedSum); // Output: Sum of mixed array: 12
const emptyArray = [];
const emptySum = sumArray(emptyArray);
console.log("Sum of empty array:", emptySum); // Output: Sum of empty array: 0