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

  • 相关阅读:
    apue学习笔记(第十五章 进程间通信)
    apue学习笔记(第十四章 高级I/O)
    apue学习笔记(第十三章 守护进程)
    各种仪器销售说明网站
    专业英语分类和查询
    c#网格控件,Excel控件
    sqlite支持linq
    使WebDev.WebServer.exe 当web服务器
    zip压缩文件测试
    c++爬虫子
  • 原文地址:https://www.cnblogs.com/ldld/p/5683540.html
Copyright © 2011-2022 走看看