Is it possible to implement null or undefined methods?

5

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

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

    
asked by anonymous 16.04.2015 / 19:30

1 answer

3

Can not extend null or a variable that is undefined . That is if you have:

a.indexOf(b);

If a is null or undefined this will give error.

Solutions?!

A variant is to use try{}catch(e){} in this 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);
    
16.04.2015 / 19:57