IE不支持数组包含(Array includes)或字符串包含(String includes)方法。

56

我一直在开发一个项目并编写 JavaScript 框架。原始代码约为 700 行,所以我只粘贴了这一行。在 Internet Explorer 上 includes 方法无效。有没有解决方法?

var row_cells = tbl_row.match(/<td[\s\S]*?<\/td>/g);

    row.Cells = new Array();
    if (onRowBindFuncText != null) { /*Fonksyon tanımlanmaışsa daha hızlı çalış*/

        var cellCount = 0;
        for (i = 0; i < row_cells.length; i++) {

            var cell = new Cell();
            $.each(this, function (k, v) {

                if ((row_cells[i]+"").includes("#Eval(" + k + ")")) {

                    cell.Keys.push(new Key(k,v));

...代码继续


有没有等效的方法?人们不会在Internet Explorer中检查一个字符串是否包含在另一个字符串中吗? :) - Onur Emrecan Özcan
5
我刚刚使用了indexOf方法解决了这个问题。 - Onur Emrecan Özcan
8个回答

75

因为在IE中不受支持,所以在Opera中也不被支持(请参阅兼容性表),但是您可以使用建议的polyfill

Polyfill

此方法已添加到ECMAScript 2015规范中,可能尚未在所有JavaScript实现中提供。但是,您可以轻松地进行polyfill:

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;
    }
  };
}

谢谢@InferOn。这是很棒的东西。我现在正在学习JavaScript,但想问一下传递到apply()中的arguments变量到底是什么?我在IE中使用console.log()查看它,发现它是某种Argument对象,但我不明白它从哪里来,因为它似乎没有被定义在任何地方。 - Yu Chen
https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Functions/arguments 可以帮助您。 - ale

50

@Infer-on 给出了很好的答案,但在特定情况下存在问题。如果您使用 for-in 循环,它将返回包括您添加的 "includes" 函数。

这是另一个 polyfill。

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;
      }
  });
}

1
使用“===”代替“==”。 - Nathan B
我可以提出一个改进建议:value: item => this.some(el => el === item) - tibalt
问题是关于字符串的 includes() 方法而不是数组。 - Pablo Pazos
当您发现第一次出现时,迭代会使性能变得不好。因此应停止迭代。 - yairniz

11

7

如果您正在寻找数组中的“includes”功能,那么这个已选答案适用于字符串。我在一个Angular项目中解决了我的问题,只需要在polyfills.ts文件中添加以下内容:

import 'core-js/es7/array';

“polyfills.ts” 是什么情况?为什么你的项目中有这个文件? - KimchiMan
1
好问题,我刚意识到当我发布我的答案时,这个问题并不特定于Angular,所以我的答案可能会让人困惑(我已经更新了它以指明它与Angular有关)。polyfills.ts是一个新的Angular(8/9/10...)项目的开箱即用的功能。 - patrickbadley

4
这是一个 TypeScript 项目的 polyfill,源自于 https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Global_Objects/Array/includes,并进行了修改以符合 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;
        }
    });
}

1
if (fullString.indexOf("partString") >= 0) {
//true 

} else {
//false
}

0
var includes = function(val, str) {
  return str.indexOf(val) >= 0;
};

0

jQuery有一个解决方案:

if ($.inArray(val,ar)===-1){
    console.log ("val not found in ar");
}
else{
    console.log ("val found in ar");
}

$.inArray(val, ar, [startingIndex]) 函数。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接