字符串数组上的jQuery.unique [英] jQuery.unique on an array of strings
问题描述
jQuery.unique()
的描述为:
The description of jQuery.unique()
states:
对DOM元素数组进行适当排序,并删除重复项.请注意,这仅适用于DOM元素数组,不适用于字符串或数字.
牢记描述,有人可以解释为什么下面的代码起作用吗?
With the description in mind, can someone explain why the code below works?
<div></div>
<div></div>
var arr = ['foo', 'bar', 'bar'];
$.each(arr, function(i, value){
$('div').eq(0).append(value + ' ');
});
$.each($.unique(arr), function(i, value){
$('div').eq(1).append(value + ' ');
});
谢谢
可能的解决方案:
function unique(arr) {
var i,
len = arr.length,
out = [],
obj = { };
for (i = 0; i < len; i++) {
obj[arr[i]] = 0;
}
for (i in obj) {
out.push(i);
}
return out;
};
推荐答案
它可以在数组字符串等上工作,但尚未针对该用途进行设计...
It might work on an array strings, etc, but it has not been designed for that use...
注意,unique()
的代码在Sizzle中隐藏为uniqueSort
: github来源
Notice that the code for unique()
is hiding in Sizzle as uniqueSort
: github source
尽管其中一些额外的代码似乎可以在任何数组上运行,但请密切注意sortOrder
While some of that extra code might seem like it would work on any array, pay close attention to sortOrder
as defined here. It does a lot of extra work to put things in "document order" - hence why the documentation states that it should only be used on arrays of DOM elements.
这篇关于字符串数组上的jQuery.unique的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!