首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Javascript startsWith原型

Javascript startsWith原型
EN

Code Review用户
提问于 2016-02-03 08:31:56
回答 1查看 141关注 0票数 1

我是JavaScript世界中的Java人,我已经习惯了关于JavaScript的某些事情,而这些东西在JavaScript中并不适用。我可以接受其中的一些,例如,String因为某种原因到处乱七八糟。

现在,我意识到这可以简单地用return this.indexOf(needle) === 0; (或者更多的JavaScripty,return this.indexOf(needle); )实现,但缺点是它将搜索整个字符串(可能有点长,你永远不知道),以便找到索引,而我真的只关心它的非零。

到目前为止,我的解决方案已经通过了我的测试。我愿意接受所有的反馈,但我最感兴趣的是

  • 打破了传统的JavaScript (坏的东西,气味)
  • 拐角处--这个案子失败了
  • 在合理的程度上,风格

我也决定把它加入课堂本身(我不得不承认,我喜欢这样做!)这是不好的做法吗?

代码语言:javascript
复制
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;

}
EN

回答 1

Code Review用户

发布于 2016-02-03 10:58:20

我建议使用String.prototype.slice来实现这样的startsWith

代码语言:javascript
复制
String.prototype.startsWith = function(str) {
  return this.slice(0, str.length) === str
}

对于类型检查(在本例中不需要,但一般情况下),您可能希望使用typeof操作符:

代码语言:javascript
复制
if (typeof str !== 'string') return false

如果处理w/的值不是文字值,或者需要检查原型链中的每个值,例如instanceof,则还可以使用str instanceof String运算符。

haystack = this?超级俗气;p,但每个人都有自己的

不确定JS是否与AIOOBE等价,但'blah'.charAt(6) === ''告诉我不需要检查。

我建议在将来使用数组迭代器而不是循环:

代码语言:javascript
复制
var haystackStartsWithNeedle = needle.split('').
  forEach((v,i) => v === haystack[i]).find(v => v)

您可能需要检查babeljs.io。它将新的和有味道的JS转换成大多数浏览器可以使用的代码。

票数 1
EN
页面原文内容由Code Review提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://codereview.stackexchange.com/questions/118742

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档