作为非 jquery 解决方案,您可以filter
像这样使用 Arrays 方法:
var thelist=["ball_1","ball_13","ball_23","ball_1"],
thelistunique = thelist.filter(
function(a){if (!this[a]) {this[a] = 1; return a;}},
{}
);
//=> thelistunique = ["ball_1", "ball_13", "ball_23"]
作为扩展Array.prototype
(使用缩短的filter
回调)
Array.prototype.uniq = function(){
return this.filter(
function(a){return !this[a] ? this[a] = true : false;}, {}
);
}
thelistUnique = thelist.uniq(); //=> ["ball_1", "ball_13", "ball_23"]
[编辑 2017 ] ES6 对此的看法可能是:
const unique = arr => [...new Set(arr)];
const someArr = ["ball_1","ball_13","ball_23","ball_1", "ball_13", "ball_1" ];
console.log( unique(someArr) );