简体   繁体   English

Data.filter在IE 8中不起作用?

[英]Data.filter not working in IE 8?

 countImage = data.filter(function(value) { return value !== undefined }).length;

This statement return error of Object doesn't support this property or method , how to fix the problem ? Object的此语句返回错误不支持此属性或方法 ,如何解决该问题? thanks 谢谢

Update , data is get from ajax and it is an array encoded using json Update ,数据是从ajax获取的,它是使用json编码的数组

$imgArray[] = $dir.DIRECTORY_SEPARATOR.$file.DIRECTORY_SEPARATOR.'Pv'.$filePadded.'.png';
die(json_encode($imgArray));

data: {'data':issueString}, 
                success: function (data) {
                    countImage = data.filter(function(value) { return value !== undefined }).length;


..........

array.filter() is not available for IE < 10, it is available in Chrome, FF and IE 10 . array.filter()不适用于IE <10,它在Chrome,FF和IE 10中可用。 so you need to use some other alternates to filter the array. 因此,您需要使用其他替代方法来过滤数组。

You can use jQuery.grep instead of fitler method 您可以使用jQuery.grep代替fitler方法

Code

var a = [1, 2, 3, 4, 5, undefined, 6, 7, undefined, 8];
alert(a.length);
var arr = jQuery.grep(a, function(n, i){
  return n != undefined;
});

alert(arr.length);

fiddle 小提琴

What you get is a javascript array and not a jquery object so you are calling on the Array.prototype.filter method. 您得到的是一个JavaScript数组,而不是一个jquery对象,因此您正在调用Array.prototype.filter方法。

If you see the compatibility for IE it is mentioned that it is supported in IE9+. 如果您看到IE的兼容性,则说明它在IE9 +中受支持。

In that page there is also a method to use for browsers that do not support Array.prototype.filter 在该页面中,还有一种方法可用于不支持Array.prototype.filter的浏览器

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

    if (this == null)
      throw new TypeError();

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

    var res = [];
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
      {
        var val = t[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, t))
          res.push(val);
      }
    }

    return res;
  };
}

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

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