Unable to extend the null
or a variable that is undefined
. That is, if you have:
a.indexOf(b);
in case the a
was null
or undefined
This is going to make a mistake.
Solutions?!
One variant is to use try{}catch(e){}
that way you create a safe zone where you can run code without stopping execution because of errors.
var result;
try{
result = a.indexOf(b);
} catch(){
result = -1;
}
Another option is to create a function to do this.
function indexOf(str, el){
if (!str && str != 0) return -1;
return str.indexOf(el);
}
var result = indexOf(a, b);
Can you explain how you want to use it? You want to modify the
indexOf()
? give an example, pf– Sergio
Yes. I want to modify it. For any time I will use it I will treat if it is null or Undefined and follow the code without error.
– Joao Paulo
For example
a.indexOf(b);
you want to treat if thea
f rnull
or theb
wasnull
? and what effectb
be itnull
?-1
?– Sergio
In case only treat if "a" is null or Undefined. And the result would be -1 if it were.
– Joao Paulo