So produzieren Sie Null beim Zugriff auf Array -Funktion in JavaScript
function average(arr){
if (arr.length === 0) return null;
let total = 0;
arr.forEach(function(item){
total += item;
})
return total / arr.length;
}
// using array.reduce() which makes more sense here
function average2(arr){
if (arr.length === 0) return null;
const total = arr.reduce(function(prev,next){
return prev + next;
});
return total / arr.length;
}
console.log(average([]));
console.log(average([1,2,3]));
console.log(average2([]));
console.log(average2([1,2,3]));
Run code snippet
de saint croissant