SCRIPT438:对象不支持 IE10 中的属性或方法"endsWith"



我有一个下面的函数,它在Chrome中运行良好,但在IE10中会出现以下错误SCRIPT438: Object doesn't support property or method 'endsWith'

function getUrlParameter(URL, param){
    var paramTokens = URL.slice(URL.indexOf('?') + 1).split('&');
    for (var i = 0; i < paramTokens.length; i++) {
    var urlParams = paramTokens[i].split('=');
    if (urlParams[0].endsWith(param)) {
        return urlParams[1];
    }
  }
}

有人能告诉我这个功能出了什么问题吗?

实现endsWith如下

String.prototype.endsWith = function(pattern) {
  var d = this.length - pattern.length;
  return d >= 0 && this.lastIndexOf(pattern) === d;
};

您应该使用以下代码在不支持endsWith的浏览器中实现它:

if (!String.prototype.endsWith) {
    String.prototype.endsWith = function(search, this_len) {
        if (this_len === undefined || this_len > this.length) {
            this_len = this.length;
        }
        return this.substring(this_len - search.length, this_len) === search;
    };
}

这直接来自Mozilla开发者网络,符合标准,与迄今为止给出的其他答案不同。

IE v.11及以下版本不支持某些ES6属性,如set、endsWith等。因此,您需要为各个ES6属性添加polyfill。为了简化这个过程,您可以使用一些编译器,如BabelJS或外部库,如polyfill.JS等。

对于结尾,在index.html中的标记之前或绑定发生之前添加以下代码段。

if (!String.prototype.endsWith) {
  String.prototype.endsWith = function(searchString, position) {
      var subjectString = this.toString();
      if (typeof position !== 'number' || !isFinite(position) || Math.floor(position) !== position || position > subjectString.length) {
        position = subjectString.length;
      }
      position -= searchString.length;
      var lastIndex = subjectString.indexOf(searchString, position);
      return lastIndex !== -1 && lastIndex === position;
  };
}

最新更新