如何高效率去掉js数组中的重复项

PHPz
Release: 2018-09-28 14:27:08
Original
1583 people have browsed it

本章给大家介绍如何高效率去掉js数组中的重复项,有一定的参考价值,有需要的朋友可以参考一下,希望对你们有所帮助。

方式一: 常规模式

1.构建一个新的临时数组存放结果

2.for循环中每次从原数组中取出一个元素,用这个元素循环与临时数组对比

3.若临时数组中没有该元素,则存到临时数组中

1.png

方式二: 使用了默认Js数组sort默认排序,是按ASCII进行排序;

若要按照升降序的排列如下:

2.png

1.先将当前数组进行排序

2.检查当前中的第i个元素 与 临时数组中的最后一个元素是否相同,因为已经排序,所以重复元素会在相邻位置

3.如果不相同,则将该元素存入结果数组中

3.png

方式三:

1.创建一个新的数组存放结果

2.创建一个空对象json

3.for循环时,每次取出一个元素与对象进行对比,如果这个元素不重复,则把它存放到结果数组中,同时把这个元素的内容作为对象的一个属性,并赋值为1,存入到第2步建立的对象中。

说明:至于如何对比,就是每次从原数组中取出一个元素,然后到对象中去访问这个属性,如果能访问到值,则说明重复。

4.png

以上就是如何高效率去掉js数组中的重复项的全部内容了,希望能给大家一个参考,更多相关教程请访问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 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!