简体   繁体   English

Javascript筛选器无法在IE9及更低版本中使用

[英]Javascript filter not working in IE9 and lower

I am getting the following error in IE 8 我在IE 8中收到以下错误

Object doesn't support this property or method

Helper.prototype.getUniqueArray = function(a) {
  /*console.log(a);*/
    return a.filter(function(elem, pos, self) {
        if (elem === '') {
            return false;
        }
        return self.indexOf(elem) === pos;
    });
};

Please help me make this work in IE9 and lower. 请帮助我在IE9及更低版本中进行此工作。

Use pollyfill for .filter() as specified at the MDN docs : 按照MDN文档中的说明,将pollyfill用于.filter()

Polyfill Polyfill

filter() was added to the ECMA-262 standard in the 5th edition; filter()已在第5版中添加到ECMA-262标准中; as such it may not be present in all implementations of the standard. 因此,它可能并不存在于该标准的所有实现中。 You can work around this by inserting the following code at the beginning of your scripts, allowing use of filter() in ECMA-262 implementations which do not natively support it. 您可以通过在脚本的开头插入以下代码来解决此问题,从而允许在本身不支持它的ECMA-262实现中使用filter()。 This algorithm is exactly the one specified in ECMA-262, 5th edition, assuming that fn.call evaluates to the original value of Function.prototype.call(), and that Array.prototype.push() has its original value. 假定fn.call计算得出Function.prototype.call()的原始值,而Array.prototype.push()具有其原始值,则该算法正是ECMA-262第5版中指定的算法。

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';

    if (this === void 0 || this === null) {
      throw new TypeError();
    }

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }

    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];

        // NOTE: Technically this should Object.defineProperty at
        //       the next index, as push can be affected by
        //       properties on Object.prototype and Array.prototype.
        //       But that method's new, and collisions should be
        //       rare, so use the more-compatible alternative.
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }

    return res;
  };
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM