浏览器支持 array.includes 和替代品

Browser support for array.includes and alternatives

我查了一下,发现这是关于在数组中的较大字符串中查找子字符串的。 Array.Prototype.includes

if (t.title.includes(searchString))

我的 t$.each 的一部分,该 $.each 遍历更大的对象数组(每个对象都从字符串、日期等中获得大量信息)。 searchString 是用户在框中键入的任何内容。所有这些都是我在页面上的列表的简单搜索功能。

这在 Chrome 中工作得很好。但是 Firefox 和 IE 出现错误

TypeError: currentTicket.title.includes is not a function

所以我要么张贴一个警告标志,表明我的应用程序只能在 Chrome 上运行,要么我手工制作一个查找功能?奇怪的是我发布的来自 MDN 的文档页面指出只有 Firefox 支持 array.includes,奇怪的是只有 Chrome 运行它。

正如您链接到的 MDN 文章所说,Firefox 仅支持 .includes 每晚构建,其他浏览器根本不支持 在文章上次更新时(Chrome 可能已更新以在以后支持它)。如果你想支持所有浏览器,你可以使用同一篇文章中概述的 polyfill:

if (![].includes) {
  Array.prototype.includes = function(searchElement /*, fromIndex*/ ) {
    'use strict';
    var O = Object(this);
    var len = parseInt(O.length) || 0;
    if (len === 0) {
      return false;
    }
    var n = parseInt(arguments[1]) || 0;
    var k;
    if (n >= 0) {
      k = n;
    } else {
      k = len + n;
      if (k < 0) {k = 0;}
    }
    var currentElement;
    while (k < len) {
      currentElement = O[k];
      if (searchElement === currentElement ||
         (searchElement !== searchElement && currentElement !== currentElement)) {
        return true;
      }
      k++;
    }
    return false;
  };
}

但是,听起来您的问题有更好的解决方案,但是没有任何细节很难说。

与其使用当前标记为 "experimental" 的 API,不如考虑使用更广泛支持的方法,例如 Array.prototype.indexOf()(IE 也支持)。

您可以使用 t.title.indexOf(string) >= 0

而不是 t.title.includes(string)

您还可以使用 Array.prototype.filter() 获取满足特定条件的新字符串数组,如下例所示。

var arr = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"];
document.getElementById("input").onkeyup = function() {
  document.getElementById("output").innerHTML = arrayContainsString(arr,this.value);
}
document.getElementById("header").innerHTML = JSON.stringify(arr);

function arrayContainsString(array, string) {
  var newArr = array.filter(function(el) {
    return el.indexOf(string) >= 0;
  });
  return newArr.length > 0;
}
<input id="input" type="text" />
<br/>
<div>array contains text:<span id="output" />
</div>
<div id="header"></div>