I created an object and put the function in it, then used the bind method to give the function some parameters, but it is undefined in the console.
let numObj = {
multyAll(...args) {
for (let i = 0; i < args.length; i ) {
if (typeof args === Number) {
arguments *= arguments[i]
return arguments
}
}
}
}
const result = numObj.multyAll.bind(1, 2, 3)
console.log(result());
I tried another way around but still, I don't know why I think the function ignores for loop and returns the value of mul which I gave in the beginning
let numObj = {
multyAll(...args) {
let mul = 1
for (arg of args) {
if (typeof arg === Number) {
mul *= arg
}
return mul
}
console.log(mul);
}
}
const result = numObj.multyAll.bind(1, 2, 3)
console.log(result());
CodePudding user response:
Some issues:
In the first version you use
arguments
which is a variable that gets automatically initialised with the function arguments. So to then use it for your product is not going to go well. The second version solves this point by using a different variablemul
, which is properly initialised to 1.In the first version,
typeof args
is testing the wrong variable. It is notargs
you want to get the type of, but ofargs[i]
. In the second version this is problem is solved.The
typeof
operator always returns a string, like "string", "number", "boolean", ... So that will never be equal toNumber
, which is a native function object, not a string.The
return
should not be inside the loop, as that will immediately stop the loop. You'll want to visit all arguments before returning, so thatreturn
must occur after the loop.bind
takes as first argument the value that should serve asthis
during the function call. The other arguments will be the normal arguments that will be passed on during the call. So you need to insert an extra argument in the first spot, likenull
.You should scope your variables and not have them implicitly defined as globals. This is the case with
arg
in the second version. Insert alet
orconst
there.Although the JavaScript engine will insert semicolons for you automatically, the rules for this can sometimes be tricky. It is better practice to take control over this yourself and separate your statements with semicolons.
Here is your second version (which was the better one) with the mentioned corrections:
const numObj = {
multyAll(...args) {
let mul = 1;
for (const arg of args) {
if (typeof arg === "number") {
mul *= arg;
}
}
return mul;
}
};
const result = numObj.multyAll.bind(null, 1, 2, 3);
console.log(result());
Finally, this task is well suited for solving with reduce
:
const numObj = {
multyAll(...args) {
return args.reduce((mul, arg) =>
mul * (typeof arg === "number" ? arg : 1),
1
);
}
};
const result = numObj.multyAll.bind(null, 1, 2, 3);
console.log(result());