zoukankan      html  css  js  c++  java
  • endsWith is not a function解决方案

    在写javascript脚本时,用某些方法,有时候会碰到"XXX is not a function"之类的报错.

    出现这种情况,主要是因为某些方法在低版本浏览器上不支持。比如说"endsWith is not a fucntion".在ES5里面,string对象是没有endsWith 方法的。

    这里可以提供2中方法解决。

    一、用lastindexOf(此方法基于对原型掌握不熟练的时候用)。

    思路如下:

    var str="5555str";

    var str2 ="str";

    //str1 是否以str2结尾

    function(str1,str2){

    if(str1.lenth<str2.length){

    return false;

    }

    var len = str1.lenth - str2.length;

    if((str1.lastIndexOf(str2)>-1)&&len===str1.lastIndexOf(str2)){

    return len;//如果是以str2结尾,则返回其在str1的索引值

    }else{

    return false;/

    }

    }

    二、修改String.prototype

    if (!String.prototype.endsWith) {
    //判断String这个对象原型是否有endsWith方法,没有的话,就用加上这个方法 Object.defineProperty(String.prototype, 'endsWith', { enumerable: false, configurable: false, writable: false, value: function (searchString, position) { position = position || this.length; position = position - searchString.length; var lastIndex = this.lastIndexOf(searchString); return lastIndex !== -1 && lastIndex === position; } });

    用了这个方法后,字符串的实例都会从从String对象的原型找到endsWith这个方法。

     

    当然,方法二更优。

    参考处:

    http://stackoverflow.com/questions/18768344/javascript-endswith-function-not-working

  • 相关阅读:
    centos 7常用需求
    python处理mysql的一些用法
    python下的queue
    2017-1-17不错的模块和工具
    wordpress钩子和钩子函数
    python中字典的使用
    linux下查看系统信息
    apk安全测试思路
    rhel 5.8 and 6.4 yum配置
    分布式文件系统
  • 原文地址:https://www.cnblogs.com/ldld/p/5683540.html
Copyright © 2011-2022 走看看