使此函数对null /空字符串等进行防御

mrb*_*lah 2 javascript

如何使这个函数对null/empty字符串更加"防御"?

function getSecondPart(str) {
    return str.split('-')[1];
}
Run Code Online (Sandbox Code Playgroud)

Pao*_*ino 7

function getSecondPart(str) {
    if(str === undefined ||
       typeof str != 'string' ||
       str.indexOf('-') == -1) return false;
    return str.split('-')[1];
}
console.log(getSecondPart({}); // false
console.log(getSecondPart([]); // false
console.log(getSecondPart()); // false
console.log(getSecondPart('')); // false
console.log(getSecondPart('test')); // false
console.log(getSecondPart('asdf-test')); // test
Run Code Online (Sandbox Code Playgroud)