es6之模拟set

class Myset {
      constructor(iterator) {
        if (typeof iterator[Symbol.iterator] != "function") {
          throw new TypeError(" object is not iterable (cannot read property Symbol(Symbol.iterator))")
        }
        this._data = [];
        for (var item of iterator) {
          this.add(item);
        }
      }
      
get size(){//没有set,因为该属性是只读的
return this._data.length;
} add(item) {
if (this.has(item)) { return; } this._data.push(item) } delete(item){ var index = this._data.findIndex(ele=>ele == item); if(index < 0){ return false; } this._data.splice(index,1); return true; } has(item) { if (this._data.indexOf(item) < 0) { return false; } return true; } *[Symbol.iterator](){ //能够用for of循环 for( var item of this._data){ yield item; } } } var myset = new Myset([1, 23, 4])
原文地址:https://www.cnblogs.com/dangdanghepingping/p/14378340.html