Javascript 为什么 .filter() 在 Internet Explorer 8 中不起作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7153470/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Why won't .filter() work in Internet Explorer 8?
提问by Hyman B
This is the line:
这是一行:
songs = songs.filter(function (el) {
return el.album==album;
});
This is the error:
这是错误:
Object doesn't support this property or method
对象不支持此属性或方法
This Works 100% fine in Chrome. What's going on?
这在 Chrome 中 100% 正常工作。这是怎么回事?
回答by Paul
Array.filter()
isn't included in IE until version 9.
Array.filter()
直到版本 9 才包含在 IE 中。
You could use this to implement it:
您可以使用它来实现它:
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;
};
}
From: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
来自:https: //developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Array/filter
Or since you are using jQuery, you can wrap your array into a jQuery object first:
或者,由于您使用的是 jQuery,您可以先将数组包装到 jQuery 对象中:
songs = $(songs).filter(function(){
return this.album==album;
});
回答by Leonardo Wong
Use es5-shim, so you can use filter/indexOf in IE8!
使用 es5-shim,这样你就可以在 IE8 中使用 filter/indexOf!
Facebook's react.js using that too.
Facebook 的 react.js 也使用了它。
<!--[if lte IE 8]>
<script type="text/javascript" src="/react/js/html5shiv.min.js"></script>
<script type="text/javascript" src="/react/js/es5-shim.min.js"></script>
<script type="text/javascript" src="/react/js/es5-sham.min.js"></script>
<![endif]-->
回答by Dennis
Does using the attr() function work?
使用 attr() 函数有效吗?
songs = songs.filter(function (index) {
return $(this).attr("album") == album;
});