为什么当searchString为空时startsWith方法返回true。我认为其他字符串方法(例如 include、endsWith)也是如此。如果我想避免它,我该怎么办,即如果 searchString 为空,它应该返回 false。
var haystack = 'Hello World!', needle ='';
console.log( haystack.startsWith( needle ) );
最佳答案
因为它被设计为返回所以。空字符串表示存在 0 个字符。这就是为什么在某种程度上,每个字符串至少以空白开头。
如果你仍然想返回false
,你可以这样做:
var haystack = 'Hello World!',
needle = '';
console.log(Boolean(needle) && haystack.startsWith(needle));
首先检查检查字符串的 bool 值,如果为空,则返回值变为false
。
关于javascript - 带有空searchString的startsWith字符串方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49567910/