Write a function that accepts a callback method and returns a function that will execute only if all the parameters passed to it are defined, otherwise it returns nothing. Here's what I wrote why is not it working?
function sumof(checkof) {
sum = 0
for (a in this.myNumbers)
if (checkof(a) == 1)
sum += a
else
return null
return sum
}
function check(a) {
if (a == null)
return 0
else
return 1
}
function init() {
let myNumbers = [22, 1, 8, 4, 17];
var x = myNumbers.sumof(check)
alert(x)
}
init()
2 Answers 2
myNumbers.sumof doesn't work because sumof is a standalone function, not part of Array.
this.myNumbers also makes no sense because myNumbers isn't global.
The simplest solution is to pass myNumbers into your sumof function:
function sumof(checkof, myNumbers) {
sum = 0
for (a in myNumbers)
if (checkof(a) == 1)
sum += a
else
return null
return sum
}
function check(a) {
if (a == null)
return 0
else
return 1
}
function init() {
let myNumbers = [22, 1, 8, 4, 17];
var x = sumof(check, myNumbers)
alert(x)
}
init()
Comments
you are calling it like a array property method. but you have defined that function as a standalone function. you should add your function as a array property method.
Array.prototype.sumof = function(checkof) {
if ( ! this.length ) {
return null;
}
sum = 0;
for (i = 0; i < this.length; i++) {
a = this[i];
if (checkof(a) == 1) {
sum += a;
}
}
return sum;
};
function check(a) {
if (a == null)
return 0;
else
return 1;
}
function init() {
let myNumbers = [22, 1, 8, 4, 17];
var x = myNumbers.sumof(check);
console.log(x);
myNumbers = [22, 1, null, 4, 17];
x = myNumbers.sumof(check);
console.log(x);
}
init();
also if you are using Array property method, you should avoid using for..in. because when you looping through this, it will also have your new method too. use for with array length.
myNumbers.sumof(...)would work?)sumof(myNumbers)\