我是JavaScript世界中的Java人,我已经习惯了关于JavaScript的某些事情,而这些东西在JavaScript中并不适用。我可以接受其中的一些,例如,String因为某种原因到处乱七八糟。
现在,我意识到这可以简单地用return this.indexOf(needle) === 0; (或者更多的JavaScripty,return this.indexOf(needle); )实现,但缺点是它将搜索整个字符串(可能有点长,你永远不知道),以便找到索引,而我真的只关心它的非零。
到目前为止,我的解决方案已经通过了我的测试。我愿意接受所有的反馈,但我最感兴趣的是
我也决定把它加入课堂本身(我不得不承认,我喜欢这样做!)这是不好的做法吗?
String.prototype.startsWith = function(needle) {
// This was dubious, if only because most times "" gets passed
// it's by mistake... but decided since it was technically correct
// that it should stay
if(needle === "") return true;
// but in all other cases, falsey values were considered false
if(!needle) return false;
// our mission, to find the needle in the haystack - is this tacky?
var haystack = this;
// primarily here to prevent AIOOBEs in the loop - is this the most
// JavaScripty way to preempt that error?
if(needle.length > haystack.length) {
return false;
}
// I've read that 'i' is not scoped to this for loop, and that I would
// need let instead. I must support older browsers, is there a better
// way to do this?
for(var i = 0; i < needle.length; i++) {
if(haystack.charAt(i) !== needle.charAt(i)) {
return false;
}
}
return true;
}发布于 2016-02-03 10:58:20
我建议使用String.prototype.slice来实现这样的startsWith:
String.prototype.startsWith = function(str) {
return this.slice(0, str.length) === str
}对于类型检查(在本例中不需要,但一般情况下),您可能希望使用typeof操作符:
if (typeof str !== 'string') return false如果处理w/的值不是文字值,或者需要检查原型链中的每个值,例如instanceof,则还可以使用str instanceof String运算符。
haystack = this?超级俗气;p,但每个人都有自己的
不确定JS是否与AIOOBE等价,但'blah'.charAt(6) === ''告诉我不需要检查。
我建议在将来使用数组迭代器而不是循环:
var haystackStartsWithNeedle = needle.split('').
forEach((v,i) => v === haystack[i]).find(v => v)您可能需要检查babeljs.io。它将新的和有味道的JS转换成大多数浏览器可以使用的代码。
https://codereview.stackexchange.com/questions/118742
复制相似问题