我在我的项目中使用以下代码:-
uniqueArray = checkboxitems.filter(function(elem, pos, self) {
return self.indexOf(elem) == pos;
})
uniqueArray 和 checkboxitems 定义为 var uniqueArray/checkboxitems = new Array();
checkboxitems 数组包含用于填充复选框并包含重复项的文本值列表。上面的代码在 Firefox 和 Google Chrome 中工作得很好,但由于 IE8 中缺少 .filter 和 .indexOf,它在该浏览器中不起作用。因此,在这里搜索并找到了对 mozillas shim 的引用,例如我尝试使用它。但这似乎不起作用。 res 数组以及我的 uniqueArray 变量从未被填充。
我还尝试使用此代码替换 a 和 unique 数组
var a = [1,5,1,6,4,5,2,5,4,3,1,2,6,6,3,3,2,4];
// note: jQuery's filter params are opposite of javascript's native implementation :(
var unique = $.makeArray($(a).filter(function(i,itm){
// note: 'index', not 'indexOf'
return i == $(a).index(itm);
}));
// unique: [1, 5, 6, 4, 2, 3]
取自使用jquery,但这又不起作用。
有人知道如何让它发挥作用吗?
谢谢 克雷格
更新我现在已经从这里使用了:- jQuery function to get all unique elements from an array?
$.extend({
distinct : function(anArray) {
var result = [];
$.each(anArray, function(i,v){
if ($.inArray(v, result) == -1) result.push(v);
});
return result;
}
});
它按我想要的方式工作。
但是我确实发现的一件事是 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf 中的代码导致索引值增加了 1 太多!但是使用这里的代码 Fixing JavaScript Array functions in Internet Explorer (indexOf, forEach, etc.)按预期工作。
最佳答案
我注意到您最初的尝试是原生/普通 JavaScript。我知道有些人对加糖内置程序不以为然,但我也需要对其进行排序。
if(!Array.prototype.unique) {
Array.prototype.unique = function () {
var nArr = [],
oLen = this.length,
dup, x, y;
for (x = 0; x < oLen; x++ ){
dup = undefined;
for (y = 0; y < nArr.length; y++ ){
if( this[x] === nArr[y] ){
dup = 1;
break;
}
}
if(!dup) { nArr.push(this[x] ); }
}
return nArr;
};
}
var myArr = ["above", "code", "works", "code", "works", "just", "and", "hence"];
var uniqueArr = myArr.unique(); //["above", "code", "works", "just", "and", "hence"]
关于javascript - 即使使用 Polyfill,在 IE 8 中也无法使用 Array.Filter,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20899908/