Home  >  Q&A  >  body text

javascript实现startswith

javascriptString.prototype.startswith = function(str) {
    return this.substr(0, str.lenth) === str;
};

验证如下,但是并没有如愿返回true

var s = 'what the fuck';
s.startswith('what')
>false

实现trim(https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/Trim)方法的时候也是这样进行的,但是为什么这个会出错?

高洛峰高洛峰2725 days ago798

reply all(3)I'll reply

  • 巴扎黑

    巴扎黑2017-04-10 14:59:26

    return this.substr(0, str.lenth) === str; // 拼写错误
    return this.substr(0, str.length) === str;
    

    reply
    0
  • ringa_lee

    ringa_lee2017-04-10 14:59:26

    因为str.lenth是undefined

    reply
    0
  • PHPz

    PHPz2017-04-10 14:59:26

    这。。。你不能把startswith该成startsWith么?
    chrome里原生自带的,不用自己写。。。--b

    reply
    0
  • Cancelreply