使用闭包时遇到问题
Having trouble using closures
我在使用闭包查找每次调用的输出平均值时遇到问题。
If the argument is undefined set it to 0 only if the first invocation is undefined. If numbers are passed return the the average of the output.
function average() {
let sum = 0;
let count = 0;
return function(num) {
let increment = count++
let avg;
if(typeof num === "number" ) {
sum += num;
// avg = sum / increment
}
return sum;
}
}
// /*** Uncomment these to check your work! ***/
const avgSoFar = average();
console.log(avgSoFar()); // => should log 0
console.log(avgSoFar(4)); // => should log 4
console.log(avgSoFar(8)); // => should log 6
console.log(avgSoFar()); // => should log 6
console.log(avgSoFar(12)); // => should log 8
console.log(avgSoFar()); // => should log 8
您需要在每次调用函数时将计数加一,然后将总和除以计数得到平均值。
function average() {
let sum = 0;
let count = 0;
return function(num) {
if(typeof num === "number" ) {
sum += num;
count++;
}
return count != 0 ? sum / count: 0;
}
}
// /*** Uncomment these to check your work! ***/
const avgSoFar = average();
console.log(avgSoFar()); // => should log 0
console.log(avgSoFar(4)); // => should log 4
console.log(avgSoFar(8)); // => should log 6
console.log(avgSoFar()); // => should log 6
console.log(avgSoFar(12)); // => should log 8
console.log(avgSoFar()); // => should log 8
我在使用闭包查找每次调用的输出平均值时遇到问题。
If the argument is undefined set it to 0 only if the first invocation is undefined. If numbers are passed return the the average of the output.
function average() {
let sum = 0;
let count = 0;
return function(num) {
let increment = count++
let avg;
if(typeof num === "number" ) {
sum += num;
// avg = sum / increment
}
return sum;
}
}
// /*** Uncomment these to check your work! ***/
const avgSoFar = average();
console.log(avgSoFar()); // => should log 0
console.log(avgSoFar(4)); // => should log 4
console.log(avgSoFar(8)); // => should log 6
console.log(avgSoFar()); // => should log 6
console.log(avgSoFar(12)); // => should log 8
console.log(avgSoFar()); // => should log 8
您需要在每次调用函数时将计数加一,然后将总和除以计数得到平均值。
function average() {
let sum = 0;
let count = 0;
return function(num) {
if(typeof num === "number" ) {
sum += num;
count++;
}
return count != 0 ? sum / count: 0;
}
}
// /*** Uncomment these to check your work! ***/
const avgSoFar = average();
console.log(avgSoFar()); // => should log 0
console.log(avgSoFar(4)); // => should log 4
console.log(avgSoFar(8)); // => should log 6
console.log(avgSoFar()); // => should log 6
console.log(avgSoFar(12)); // => should log 8
console.log(avgSoFar()); // => should log 8