高效率去掉js数组中重复项
来源:互联网 发布:日亚海淘攻略 知乎 编辑:程序博客网 时间:2024/06/06 03:53
第一种:也是最笨的吧。
Array.prototype.unique1 =
function
() {
var
r =
new
Array();
label:
for
(
var
i = 0, n =
this
.length; i < n; i++) {
for
(
var
x = 0, y = r.length; x < y; x++) {
if
(r[x] ==
this
[i]) {
continue
label;
}
}
r[r.length] =
this
[i];
}
return
r;
}
第二种:这个正则天书一样。
Array.prototype.unique2 =
function
() {
return
this
.sort().join(
",,"
).replace(/(,|^)([^,]+)(,,\2)+(,|$)/g,
"$1$2$4"
).replace(/,,+/g,
","
).replace(/,$/,
""
).split(
","
);
}
第三种:使用对象的【hasOwnProperty】方法
Array.prototype.unique3 =
function
() {
var
temp = {}, len =
this
.length;
for
(
var
i=0; i < len; i++) {
var
tmp =
this
[i];
if
(!temp.hasOwnProperty(tmp)) {
temp[
this
[i]] =
"my god"
;
}
}
len = 0;
var
tempArr=[];
for
(
var
i
in
temp) {
tempArr[len++] = i;
}
return
tempArr;
}
第四种:先排序,前项比后项。这个方法挺简单的,但也实用。
Array.prototype.unique4 =
function
() {
var
temp =
new
Array();
this
.sort();
for
(i = 0; i <
this
.length; i++) {
if
(
this
[i] ==
this
[i+1]) {
continue
;
}
temp[temp.length]=
this
[i];
}
return
temp;
}
下面是以前经常用的,效率也很好。有点想hash表的感觉。
Array.prototype.unique5 =
function
() {
var
res = [], hash = {};
for
(
var
i=0, elem; (elem =
this
[i]) !=
null
; i++) {
if
(!hash[elem])
{
res.push(elem);
hash[elem] =
true
;
}
}
return
res;
}
使用方法:yourarray=yourarray.unique4();//你的数组名、unique1 2 3 4 5、、
0 0
- 高效率去掉js数组中重复项
- 高效率去掉js数组中重复项
- 高效率去掉js数组中重复项
- 高效率去掉js数组中重复项
- 高效率去掉js数组中重复项
- 高效率去掉js数组中重复项
- 高效率去掉js数组中重复项
- JS数组高效率去除重复
- 去掉JS数组中重复的元素
- 去掉JS数组中重复的元素
- JS 去掉数组重复值
- js 去掉重复的 数组
- JS数组去掉重复元素
- 去除数组中重复的元素,高效率
- JavaScript中数组去掉重复的项
- 去掉数组中重复项之越过重复值法
- js中去掉重复键值
- js 字符串类型的数组去掉重复项
- Minio: 非结构化对象存储服务提供者
- 一些大学学过的排序
- Ubuntu Linux更改PATH路径
- bash编程之${ }用法总结
- poj 1050 解题报告 [动态规划] [最大子段和]
- 高效率去掉js数组中重复项
- 第三周项目4-顺序表应用1
- 第三周项目4
- Android面试
- 设计模式_模版模式(Template Pattern)
- iconfont 网站
- andeoid4.x强制使用TLSv1.2
- 三周
- 【Linux内核设计与实现】进程管理