IE does not support Array includes or String includes methods

后端 未结 7 1227
温柔的废话
温柔的废话 2020-11-29 06:04

I have been working on a project and developing a JavaScript framework. The original code is about 700 lines so I only pasted this line. The includes method doesn\'t work on

相关标签:
7条回答
  • 2020-11-29 06:06

    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;
        }
      };
    }
    
    0 讨论(0)
  • 2020-11-29 06:12

    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';
    
    0 讨论(0)
  • 2020-11-29 06:14
    var includes = function(val, str) {
      return str.indexOf(val) >= 0;
    };
    
    0 讨论(0)
  • 2020-11-29 06:17
    if (fullString.indexOf("partString") >= 0) {
    //true 
    
    } else {
    //false
    }
    
    0 讨论(0)
  • 2020-11-29 06:18

    @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;
          }
      });
    }
    
    0 讨论(0)
  • 2020-11-29 06:26

    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) {
    
    0 讨论(0)
提交回复
热议问题