Object.includes 不是旧 Chrome 中的函数

Object.includes is not a function in old Chrome

我正在不同设备上测试 WebView。 在旧版本中(WebView in com.com.com (39.0.0.0)),这个功能不起作用:

var obj = $.parseJSON( data );
    console.log(obj);
    objectManager.setFilter(function(geoObject) { 
        return obj.includes(geoObject.id);   <---- 1839 Error
    });

日志:

VM203 cmap-ya-android.js:1837 ["25", "59", "63"]
VM203 cmap-ya-android.js:1839 Uncaught TypeError: undefined is not a function
VM203 cmap-ya-android.js:1839 (anonymous function)
......

在新 Chrome 中一切正常:com.com.com 中的 WebView (69.0.3497.100)

此方法根据文档过滤标记在地图上的显示:

https://tech.yandex.com.tr/maps/jsapi/doc/2.1/ref/reference/ObjectManager-docpage/#method_detail__setFilter-param-filterFunctionhttps://yandex.ru/blog/mapsapi/setfilter-peredat-massiv-dannykh

告诉我,我该如何调整 Object.include 以适应旧设备? (或者创建一个适用于所有版本的过滤器)

我假设您的 obj 变量实际上是一个数组,如您日志的第一行所示。这意味着您正在项目中使用 Mozilla JS 文档中的 Array.includes() instead of Object.includes. You can support older browsers by including this polyfill。这将为 Array.includes 添加一个实现(如果它尚不存在)。

当您需要在旧版浏览器中支持更新的浏览器功能时,您可以随时搜索 polyfills


如果带有 polyfill 的 link 永远死掉,这里是该页面的代码:

// https://tc39.github.io/ecma262/#sec-array.prototype.includes
if (!Array.prototype.includes) {
  Object.defineProperty(Array.prototype, 'includes', {
    value: function(searchElement, fromIndex) {

      // 1. Let O be ? ToObject(this value).
      if (this == null) {
        throw new TypeError('"this" is null or not defined');
      }

      var o = Object(this);

      // 2. Let len be ? ToLength(? Get(O, "length")).
      var len = o.length >>> 0;

      // 3. If len is 0, return false.
      if (len === 0) {
        return false;
      }

      // 4. Let n be ? ToInteger(fromIndex).
      //    (If fromIndex is undefined, this step produces the value 0.)
      var n = fromIndex | 0;

      // 5. If n ≥ 0, then
      //  a. Let k be n.
      // 6. Else n < 0,
      //  a. Let k be len + n.
      //  b. If k < 0, let k be 0.
      var k = Math.max(n >= 0 ? n : len - Math.abs(n), 0);

      // 7. Repeat, while k < len
      while (k < len) {
        // a. Let elementK be the result of ? Get(O, ! ToString(k)).
        // b. If SameValueZero(searchElement, elementK) is true, return true.
        // c. Increase k by 1.
        // NOTE: === provides the correct "SameValueZero" comparison needed here.
        if (o[k] === searchElement) {
          return true;
        }
        k++;
      }

      // 8. Return false
      return false;
    }
  });
}

根据 https://caniuse.com/#feat=array-includes,旧版浏览器不支持 Array.prototype.includes。 请使用 indexOf 重写代码或使用 polyfill。

在这里您可以使用

实现相同的效果
var obj = $.parseJSON( data );
console.log(obj);
objectManager.setFilter(function(geoObject) { 
    return obj.indexOf(geoObject.id) > -1;  
});