如何使这个函数对null/empty字符串更加"防御"?
function getSecondPart(str) {
return str.split('-')[1];
}
Run Code Online (Sandbox Code Playgroud)
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)
归档时间: |
|
查看次数: |
185 次 |
最近记录: |