Equivalent of set in ES6 to ES5

前端 未结 3 835
闹比i
闹比i 2020-12-21 05:15

I have a set over which I am iterating in ES6. I am trying to convert it to its equivalent in ES5. My build is getting failed because of ES6. That\'s why I am converting it

相关标签:
3条回答
  • 2020-12-21 05:40

    Why not just iterate through the data and map the result with Array#map.

    result = deviceList.map(function (item) {
        return { deviceName: item };
    });
    
    0 讨论(0)
  • 2020-12-21 05:44

    I think your problem with your second for example is just that length is a property and not a function so you shouldn't add () to the end of it. A working version of this might look like this:

    for(var i = 0; i < deviceList.length; i++){
      result.push({"deviceName" : deviceList[i]});
    }
    

    This assumes (as @grabantot pointed out) that deviceList is an array, however, if it's a Set then you need to use the deviceList.size property.

    However, there is a more compatible version of your first for loop which is the forEach() function (which is available on Array and Set), like this:

    deviceList.forEach(function (item) {
      result.push({"deviceName": item});
    });
    
    0 讨论(0)
  • 2020-12-21 05:53

    This is a basic set es5 class that I have used variations on over the years.

    function Set(items) {
      this._data = {};
      this.addItems(items);
    }
    
    Set.prototype.addItem = function(value) {
      this._data[value] = true;
      return this;
    }
    
    Set.prototype.removeItem = function(value) {
      delete this._data[value];
      return this;
    }
    
    Set.prototype.addItems = function(values) {
      for (var i = 0; i < values.length; i++) {
        this.addItem(values[i]);
      }
      return this;
    }
    
    Set.prototype.removeItems = function(values) {
      for (var i = 0; i < values.length; i++) {
        this.removeItem(values[i]);
      }
      return this;
    }
    
    Set.prototype.contains = function(value) {
      return !!this._data[value];
    }
    
    Set.prototype.reset = function() {
      this._data = {};
      return this;
    }
    
    Set.prototype.data = function() {
      return Object.keys(this._data);
    }
    
    Set.prototype.each = function(callback) {
      var data = this.data();
      for (var i = 0; i < data.length; i++) {
        callback(data[i]);
      }
    }
    
    var set = new Set(['a', 'b', 'c']);
    console.log(set.addItems(['a', 'd', 'e']).removeItems(['b', 'e']).data());
    console.log(set.contains('a'));
    console.log(set.contains('e'));
    
    set.each(console.log)

    0 讨论(0)
提交回复
热议问题