js数组去重的方法汇总_javascript技巧

WBOY
Release: 2016-05-16 15:48:09
Original
1333 people have browsed it

三种方法

利用indexOf判断新数组

underscore.js中实际上也是使用的类似的indexOf

//传入数组 function unique1(arr){ var tmpArr = []; for(var i=0; i
         
Copy after login

利用indexOf判断旧数组

function unique2(arr){ var tmpArr = []; //结果数组 for(var i=0; i
         
Copy after login

利用hash查找

这里利用了JS对象的实现就是hash表的特性

function unique3(arr){ var tmpArr = [], hash = {};//hash为hash表 for(var i=0;i
         
Copy after login

数组扩展

Array.prototype.unique1 = function (){ var tmpArr = []; for (var i = 0; i < this.length; i++){ if (tmpArr.indexOf(this[i]) == -1){ tmpArr.push(this[i]); } } return tmpArr; } Array.prototype.unique2 = function(){ var tmpArr = []; //结果数组 for(var i = 0; i < this.length; i++){ if (this.indexOf(this[i]) == i){ tmpArr.push(this[i]); } } return tmpArr; } Array.prototype.unique3 = function(){ var tmpArr=[], hash = {}; for(var i = 0; i < this.length; i++){ if (!hash[this[i]]){ hash[this[i]] = true; tmpArr.push(this[i]); } } return tmpArr; }
Copy after login

使用Set

Set和Map是ES6中新增的数据结构
Set直接可以存储不重复的一组key,这个key也可以是对象,字符串等
创建set

var s = new Set([1, 2, 3,]); s; // Set {1, 2, 3}
Copy after login

新增元素

>>> s.add(4) >>> s {1, 2, 3, 4} >>> s.add(4) >>> s {1, 2, 3, 4}//重复元素不会被添加
Copy after login

删除元素

s; // Set {1, 2, 3, 4} s.delete(3); s; // Set {1, 2, 4}
Copy after login

遍历元素

Map和Set无法使用下标
ES6标准引入了新的iterable类型,Array、Map和Set都属于iterable类型

var s = new Set(['A', 'B', 'C']); for (var x of s) { // 遍历Set alert(x); }
Copy after login

或者直接使用iterable内置的forEach方法
forEach方法是ES5.1标准引入的

var s = new Set(['A', 'B', 'C']); s.forEach(function (element, set) { alert(element); });
Copy after login

以上所述就是本文的全部内容了,希望大家能够喜欢。

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!