3

#yyds干货盘点# 前端歌谣的刷题之路-第一百一十六题-数组去重

 1 year ago
source link: https://blog.51cto.com/u_14476028/5757489
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
neoserver,ios ssh client

#yyds干货盘点# 前端歌谣的刷题之路-第一百一十六题-数组去重

精选 原创

前端歌谣 2022-10-14 16:35:20 ©著作权

文章标签 数组 html 文章分类 JavaScript 前端开发 yyds干货盘点 阅读数224

我是歌谣 我有个兄弟 巅峰的时候排名c站总榜19 叫前端小歌谣 曾经我花了三年的时间创作了他 现在我要用五年的时间超越他 今天又是接近兄弟的一天人生难免坎坷 大不了从头再来 歌谣的意志是永恒的 放弃很容易 但是坚持一定很酷 本题目源自于牛客网 微信公众号前端小歌谣

为 Array 对象添加一个去除重复项的方法

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN] 输出:

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a']

<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>数组去重</title>
</head>

<body>
<!-- 为 Array 对象添加一个去除重复项的方法
示例1
输入:

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a', 'a', NaN]

输出:

[false, true, undefined, null, NaN, 0, 1, {}, {}, 'a'] -->
<script>Array.prototype.uniq = function () {
return Array.from(new Set(this))
}
</script>
</body>

</html>

Set数据结构类似于数组,但里面的成员都是唯一的。判断是否唯一的标准基本等同于‘===’,唯一的区别在于,‘===’判断时NaN与NaN不相等,但Set会认为它们相等并去重。
由于Set只是类似数组,所以要用Array.from返回一个真正的数组。


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK