Using ES5 array methods with ES6 generators

前端 未结 3 1581
刺人心
刺人心 2020-12-20 16:28

What\'s the correct way of using the new ES5 array functions with ES6 generators? Do I have to explicitly convert the iterable into an array first, or is there a better way?

3条回答
  •  被撕碎了的回忆
    2020-12-20 17:06

    Since Array.from does not work on Chrome at the current time, I needed another way to convert an Iterator into an Array.

    (though of course you can shim it with a polyfill)

    function iterator2Array(iterator) {
        var result = [];
        for (var item in iterator) {
            result.push(item)
        }
        return result;
    }
    

    For similar reasons I add a "toArray" to the prototype of a Map so that I basically convert an iterator into an Array so that you can use its functional-oriented methods; of course each item of the array will be a [key, value] tuple (exactly like in its Map.entries())

    if (!Map.prototype.toArray) {
        /**
         * Transforms a map into an Array of 'tuples' [[key, value], ...]
         */
        Map.prototype.toArray = function () {
            var result = [];
    
            for (var item of this) {
                result.push(item);
            }
    
            return result;
        }
    }
    
    var m = new Map([[0, 0], ['a', 'A']]);
    m.toArray()
    

    Then you can use it as an array - remember the [key, value] approach though!

    m.toArray().map(
        function(item, index, array) {
            var key = item[0],
            value = item[1];
            console.log(key + ": " + value);
            return value;
    });
    

    This will return the values of the map (ok not superuseful of course!)

    If you prefer a more standar looking loop:

    var i = iterator.entries(),
        result = [],
        value;
    while (value = i.next().value) {
        result.push(value);
    }
    

提交回复
热议问题