set对象

Set 对象允许你存储任何类

用于存储任何类型的唯一值,无论是基本类型还是对象引用。

  • 只能保存值没有键名

  • 严格类型检测如字符串数字不等于数值型数字

  • 值是唯一的

  • 遍历顺序是添加的顺序,方便保存回调函数

声明

里面以数组赋予

  <script>	
    const set = new Set("bushigemen")
    console.log(set)//Set(9) {'b', 'u', 's', 'h', 'i', …}
    const set1 = new Set([1, 2, 3, 4, 5])
    console.log(set1)//Set(5) {1, 2, 3, 4, 5}
    const set2 = new Set(["ew", "set"])
    console.log(set2)//Set(2) {'ew', 'set'}
	//
	const set3 = new Set('f')
    console.log(set3)//Set(1) {'f'}
    const set4 = new Set(1)
    console.log(set4)//TypeError: number 1 is not iterable (cannot read property Symbol(Symbol.iterator)),错误
	const obj = {
      1: 222,
      2: 111
    }
    const set5 = new Set(obj)
    console.log(set5)//错误
const arr = [1, 2, 3]
    const set6 = new Set(arr)
    console.log(set6)//Set(3) {1, 2, 3}
  </script>

方法:

1.获取元素数量

let hd = new Set();
hd.add('ad');
console.log(hd.has('ad'));//true

2.检测元素

let set = new Set(['as', 'df']);
console.log(hd.size); //2

3.添加 

let hd = new Set();

hd.add('ad');

4.删除

1. 使用 delete 方法删除单个元素,返回值为boolean类型

2. 使用 clear 删除所有元素

let hd = new Set();
hd.add("ad");
hd.add("df");
console.log(hd.delete("ad")); //true
hd.clear();

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值