首页 > 开发 > JS > 正文

ES6 Set结构的应用实例分析

2024-05-06 16:52:46
字体:
来源:转载
供稿:网友

本文实例讲述了ES6 Set结构的应用。分享给大家供大家参考,具体如下:

Set 类似于数组,但是成员的值都是唯一的,没有重复的值, 实现了iterator接口

set 的值不可重复,数组的值可以重复

let arr = [1,2,3,'5','5'];let st = new Set(arr);console.log(st); // 可以通过set来去除数组的重复的值,返回的是一个伪数组console.log(st.size); // 4

set 的 add , delete, has, clear 方法

简单的add 与 delete :

let st = new Set();var u = {name:'Joh'};st.add(u);let bool = st.delete(u);console.log(bool); // true;

连续add与has的api :

let st = new Set();var u = {name:'Joh'};var r = {name:'Lily'};st.add(u).add(r);let bool = st.delete(r);console.log(bool); // trueconsole.log(st.has(r)); // falseconsole.log(st.has(u)); // true;

clear清空set集合

let st = new Set();var u = {name:'Joh'};var r = {name:'Lily'};st.add(u).add(r);st.clear();console.log(st.size); // 0

通过Array.from方法把类似数组结构的模型转化为数组

let arr = ['xxx', 'yyyy', 'yyyy'];let newArr = Array.from(new Set(arr));console.log(Array.isArray(newArr)); // trueconsole.log(newArr); // ["xxx", "yyyy"]

Set 原型上的Symbol.iterator 和 values 是同一个值, 可直接for-of遍历

console.log(Set.prototype[Symbol.iterator] === Set.prototype.values); // truelet st = new Set(['xxx', 'yyyy', 'yyyy', 'John']);for(let k of st) { console.log(k); // 依次输出 xxx yyyy John 可以直接遍历,兼容map的数据结构}

set中的keys和values方法

let st = new Set(['xxx', 'yyyy', 'yyyy', 'John']);console.log(st.size); // 3let itKeys = st.keys();for(let k of itKeys) {   console.log(k); // 依次输出 xxx yyyy John}console.log('>>>>>');let itVals = st.values();for(let v of itVals) {   console.log(v); // 依次输出 xxx yyyy John}

set 的entries 实体对象,是个键和值的数组结构

let st = new Set(['xxx', 'yyyy', 'yyyy', 'John']);let entriesIt = st.entries(); //for(let v of entriesIt) { console.log(v); // 依次输出 ["xxx", "xxx"] ["yyyy", "yyyy"] ["John", "John"]}

关于NaN在set中的特殊性

let st = new Set();console.log(NaN === NaN); // false , 此处 NaN 是不全等的,理应可以添加多个,不算重复,但是这里是个特例st.add(NaN).add(NaN).add(NaN);for(let v of st) { console.log(v); // 只输出一个 NaN}

 

希望本文所述对大家JavaScript程序设计有所帮助。


注:相关教程知识阅读请移步到JavaScript/Ajax教程频道。
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表