javascript在IE8下不支持filter的解决方案

来源:互联网 发布:手机影子软件 编辑:程序博客网 时间:2024/06/01 08:54

这是代码:

songs = songs.filter(function (el) {  return el.album==album;});  

这是错误:

Object doesn't support this property or method

提出问题:这个属性在chorme中100%的支持,而在IE8中出现错误这是怎么回事?

回答:因为在IE9之前,Array.filter()不包含在IE中。
你可以用下面这段代码来实现它:

if (!Array.prototype.filter){  Array.prototype.filter = function(fun /*, thisp */)  {    "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 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;  };}

或者你可以选择使用jQuery,您可以先将数组打包成一个jQuery对象:

songs = $(songs).filter(function(){  return this.album==album;}); 
阅读全文
1 0
原创粉丝点击