Is it possible to implement null or Undefined methods?

Asked

Viewed 52 times

5

If I wanted to implement a variable check whenever I would use the method .indexOf() javascript this would be possible?

For example using a.indexOf(b); it is possible to detect when the a is null or undefined and change the method to return -1?

  • 1

    Can you explain how you want to use it? You want to modify the indexOf()? give an example, pf

  • 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.

  • 1

    For example a.indexOf(b); you want to treat if the a f r null or the b was null ? and what effect bbe it null? -1?

  • In case only treat if "a" is null or Undefined. And the result would be -1 if it were.

1 answer

3


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);

Browser other questions tagged

You are not signed in. Login or sign up in order to post.