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

    技术2024-08-20  164

    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);
    Processed: 0.013, SQL: 9