(精华)2020年7月3日 JavaScript高级篇 ES6(Set数据结构)

Set是什么

// Set是es6新提出的一个新的引用数据类型 类似于数组 但是成员是唯一的 没有重复的值
// 和对象里面的 get  set 不一样

基本用法

// 基本用法
const set = new Set([1,2,3,4,5,6,5])
console.log(set);

证明set是js新的引用数据类型

let arr = [1,2,3,4]
let obj = {name:'张三'}
let nu = null // 历史遗留问题
console.log(typeof arr);
console.log(typeof obj);
console.log(typeof nu);
// 证明 arr是数组  obj 是对象
// instanceof 
// Object.prototype.toString.call(arr)
console.log(arr instanceof Array);
console.log(obj instanceof Object);
console.log(Object.prototype.toString.call(arr)); // string [object Array]
console.log(Object.prototype.toString.call(obj)); // string [object Object]
const set = new Set([1,2,3,4,5,6,5])
console.log(set instanceof Set);
console.log(Object.prototype.toString.call(set) === '[object Set]');

转化成数组

// 转化成数组
const set = new Set([1,2,3,4,5,6,5])
// 数组去重的方法
console.log([...set]);
console.log(Array.from(set));

Set数据内部判断值得机制

// Set数据内部判断值得机制 类似于 === 
let newSet = new Set()
let a = 5;
let b = '5'
newSet.add(a)
newSet.add(b)
// ? 里面有几项 ?
console.log(newSet);
// 特殊情况NaN 
// 因为 NaN === NaN 
newSet.add(NaN)
newSet.add(NaN)
console.log(newSet);

Set实例的属性和方法

Set的属性

let lastSet = new Set()
lastSet.add(1).add(2).add(2).add('2').add(NaN).add(NaN)
console.log(lastSet.size);

add delete has clear

let lastSet = new Set()
lastSet.add(1).add(2).add(2).add('2').add(NaN).add(NaN)
console.log(lastSet.size);
// 判断是否有这一项
console.log(lastSet.has(2));
lastSet.clear()
console.log(lastSet);

并集 交集 差集

let arr1 = [1, 2, 3]
let arr2 = [4, 3, 2]
// 并集 交集 差集 set ...
let a = new Set(arr1)
let b = new Set(arr2)
let union = new Set([...a, ...b])
console.log(union);
// Array.from ...
// 交集
let inter = new Set([...a].filter(function (x) {
    return b.has(x)
}))
console.log(inter);
// 差集
let difference = new Set([...a].filter(function (x) {
    return !b.has(x)
}))
console.log(difference);
  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

愚公搬代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值