JavaScript中数组去除重复的三种方法_javascript技巧

WBOY
Release: 2016-05-16 15:04:30
Original
1081 people have browsed it

废话不多说了,具体方法如下所示:

方法一:返回新数组每个位子类型没变

function outRepeat(a){ var hash=[],arr=[]; for (var i = 0; i < a.length; i++) { hash[a[i]]!=null; if(!hash[a[i]]){ arr.push(a[i]); hash[a[i]]=true; } } console.log(arr); } outRepeat([2,4,4,5,"a","a"]);//[2, 4, 5, "a"]
Copy after login

方法二:类似于法一,但本农觉着法一更易于理解

function outRepeat(a){ var hash=[],arr=[]; for (var i = 0,elem;(elem=a[i])!=null; i++) { if(!hash[elem]){ arr.push(elem); hash[elem]=true; } } console.log(arr); } outRepeat([2,4,4,5,"a","a"]);//[2, 4, 5, "a"]
Copy after login

方法三:比前两个更易于理解但是返回的新数组每个位子的number类型变为string类型了!!关键时刻得处理

function outRepeat(a){ var hash=[],arr=[]; for (var i = 0; i < a.length; i++) { hash[a[i]]=null; } for(var key in hash){ arr.push(key); } console.log(arr); } outRepeat([2,4,4,5,"a","a"]);//["2", "4", "5", "a"]
Copy after login

以上是小编给大家介绍的JavaScript中数组去除重复的三种方法,希望对大家有所帮助!

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 Articles by Author
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!