我知道在 IE8 中不支持数组过滤功能。在互联网上寻求帮助后,我发现了这个 - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/filter
它表明 IE8 将使用上面的代码工作。
HTML 代码:
<body>
<a href="javascript:void(0)" onclick="calculateDiff()">Calculate</a>
</body>
JS代码:
function calculateDiff() {
var arr1 = new Array(1, 2, 3);
var arr2 = new Array(3, 4, 5);
var res = arr1.diff(arr2);
alert(res);
}
Array.prototype.diff = function(a) {
if(!Array.prototype.filter) {
alert("not supported");
Array.prototype.filter = function(fun) {
"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;
};
}
else {
alert("supported");
return this.filter(function(i) {
return !(a.indexOf(i) > -1);
});
}
}
我已经在这个小提琴中实现了解决方案 - http://jsfiddle.net/7LFMA/
代码有什么问题?为什么它不起作用?