3
I am trying to call a function which is a property of an object, passing a parameter to it. For this I use bracket notation plus this: (parâmetro)
.
Thus:
afraid[day](num.toString())
But returns error:
afraid[day] is not a Function.
I tried with string template too:
afraid[`${day}`](num.toString())
and also:
afraid[`"${day}"`](num.toString())
and makes the same mistake:
Typeerror: afraid[((""" +] is not a Function
It only works if I pass the object property name as a literal string, but it’s not what I need:
afraid["Tuesday"](num.toString())
See the function on the object:
let afraid = {
Monday: 12,
Tuesday: function(number){
if(number>95)return true
else return false
},
Wednesday: 34,
Thursday: 0,
Fryday: function(number){
if(number%2 == 0) return true
else return false
},
Saturday: 56,
Sunday: 666
}
And the attempt to use the function:
if(afraid[day] == Math.abs(num) || afraid[`${day}`](num.toString()) == true) return true
else return false
Not all the keys to
afraid
are functions, the error does not occur only whenday
it is neither 'Tuesday' nor 'Fryday'? https://ideone.com/Jj09v3– hkotsubo
Are you sure the value of
day
is what is expected?– Costamilam
But your object itself, the keys of the functions are literal strings, if you have a return of the literal keys within this day object, just do this:
afraid[(day).toString()](num.toString())
– Ivan Ferrer
What exactly is returning:
day
? that has in this:const day = "???"
– Ivan Ferrer
@hkotsubo. It makes sense, because not all day properties are functions, but I didn’t think it would give error when testing an if.
– Lucas Pletsch
@Ivanferrer day is a string
– Lucas Pletsch