Set

一个存储任意类型的结构,且保证成员是独一无二的。与数组不同的是,不能用下标访问Set内的成员。

const people = new Set();

API

  • add():类似于数组中的push,添加成员
  • size:获取长度,而不是用length
    people.add('one');
    people.add('day');
    people.add('oneday'); //Set(3) {"one", "day", "oneday"}
    people.size; // 3
    
  • values():将set内的成员变成一个Generator,可以进行next()操作
    const it = people.values();
    it.next(); // {value: "one", done: false}
    it.next(); // {value: "day", done: false}
    it.next(); // {value: "oneday", done: false}
    it.next(); // {value: undefined, done: true}
    
  • delete():删除一个元素
    people.delete('oneday');  // Set(2) {"one", "day"}
    
  • has():判断是否含有某个成员
    people.has('one')); //true
    people.has('oneday')); //false
    
  • keys():遍历
  • entries():也是遍历
  • for...of:还是遍历
  • forEach(callback):可以添加一个callback函数的遍历
    people.keys(); // SetIterator {"one", "day"}
    people.entries(); // SetIterator {"one", "day"}
    for (person of people) {
      console.log(person); // one \n day
    }
    people.forEach((value) => {
      console.log(value + 'aaa') // oneaaa \n dayaaa
    })
    
  • clear():清空set
    people.clear(); // Set(0) {}
    

results matching ""

    No results matching ""