<!DOCTYPE html>
<html lang="en">
<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>Document</title>
</head>
<body>
<script>
/*
ES6提供新的数据结构set,类似于数组,但是里面成员的值都是唯一的
*/
// 创建方法1:
let s = new Set();
//forEach是用于遍历,取出字符串的值赋到x中
[1,2,3,3,4].forEach(x => s.add(x));
console.log(s);
// 创建方法2:接收一个数组作为参数
let s1 = new Set([1,2,3,4,5,4])
console.log(s1);
// 数组去重复成员方法
let array = [1,2,2,2,3,4]
// let s2 = new Set(array)
// console.log([...s2]);
// 等同于
console.log([...new Set(array)]);
// 字符串去重复字符: 先转换为数组,再用join('')转为字符串
// let arr = 'abcdddd'
// let s3 = new Set(arr)
// console.log([...s3].join(''));
// 等同于
console.log([...new Set('abcdddd')].join(''));
// 当Set加入值时,不会发生类型转换,所以5和'5'是两个值
let s4 = new Set([5,'5'])
console.log(s4);
// size属性:返回成员总数
console.log(s4.size);
</script>
</body>
</html>
14.ES6新特性:Set数据结构
最新推荐文章于 2024-07-25 09:24:40 发布