ie does not support 'includes' method

爷,独闯天下 提交于 2019-11-27 08:12:19
alessandro

Because it's not supported in IE, it is not supported also in Opera (see the compatibility table), but you can use the suggested polyfill:

Polyfill

This method has been added to the ECMAScript 2015 specification and may not be available in all JavaScript implementations yet. However, you can easily polyfill this method:

if (!String.prototype.includes) {
  String.prototype.includes = function(search, start) {
    'use strict';
    if (typeof start !== 'number') {
      start = 0;
    }

    if (start + search.length > this.length) {
      return false;
    } else {
      return this.indexOf(search, start) !== -1;
    }
  };
}

@Infer-on shown great answer, but it has a problem in a specific situation. If you use for-in loop it will return includes "includes" function you added.

Here is another pollyfill.

if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, "includes", {
    enumerable: false,
    value: function(obj) {
        var newArr = this.filter(function(el) {
          return el == obj;
        });
        return newArr.length > 0;
      }
  });
}

You could just use .search() > -1 which behaves in the exact same way. http://www.w3schools.com/jsref/jsref_search.asp

if ((row_cells[i]+"").search("#Eval(" + k + ")") > -1) {

This Selected answer is for String, if you are looking for 'includes' on an array, I resolved my issue by adding the following to my polyfills.ts file:

import 'core-js/es7/array';

This is a polyfill for TypeScript projects, taken from https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/includes and modified to be valid TypeScript:

if (!Array.prototype.includes) {
    Object.defineProperty(Array.prototype, 'includes', {
        value: function(searchElement, fromIndex) {

            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            const o = Object(this);
            // tslint:disable-next-line:no-bitwise
            const len = o.length >>> 0;

            if (len === 0) {
                return false;
            }
            // tslint:disable-next-line:no-bitwise
            const n = fromIndex | 0;
            let k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

            while (k < len) {
                if (o[k] === searchElement) {
                    return true;
                }
                k++;
            }
            return false;
        }
    });
}
if (fullString.indexOf("partString") >= 0) {
//true 

} else {
//false
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!