微服务 教程
1085个小节阅读:196.6k
目录
C语言快速入门
JAVA全系列 教程
面向对象的程序设计语言
Python全系列 教程
Python3.x版本,未来主流的版本
人工智能 教程
顺势而为,AI创新未来
大厂算法 教程
算法,程序员自我提升必经之路
C++ 教程
一门通用计算机编程语言
微服务 教程
目前业界流行的框架组合
web前端全系列 教程
通向WEB技术世界的钥匙
大数据全系列 教程
站在云端操控万千数据
AIGC全能工具班
A A
White Night
ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
Set
本身是一个构造函数,用来生成 Set 数据结构。
xxxxxxxxxx
const s = new Set();
[2, 3, 5, 4, 5, 2, 2].forEach(x => s.add(x));
for (let i of s) {
console.log(i);
}
// 2 3 5 4
通过add()
方法向 Set 结构加入成员,结果表明 Set 结构不会添加重复的值。
Set
函数可以接受一个数组作为参数
xxxxxxxxxx
const set = new Set([1, 2, 3, 4, 4]);
[...set]
// [1, 2, 3, 4]
数组去除重复成员的方法
xxxxxxxxxx
// 去除数组的重复成员
[...new Set(array)]
字符串去除重复字符
xxxxxxxxxx
[...new Set('ababbc')].join('')
// "abc"
向 Set 加入值的时候,不会发生类型转换,所以5
和"5"
是两个不同的值。
xxxxxxxxxx
var mySet = new Set();
mySet.add("5")
mySet.add(5)
console.log(mySet); // Set(2) {'5', 5}
返回Set
实例的成员总数
xxxxxxxxxx
const items = new Set([1, 2, 3, 4, 5, 5, 5, 5]);
items.size // 5
实时效果反馈
1. 下列代码输出结果是多少:
xxxxxxxxxx
var mySet = new Set();
mySet.add("5")
mySet.add(5)
mySet.add(5)
console.log(mySet);
A "5" 5 5
B "5" 5
C "5"
D null
答案
1=>B