Spread Operator equivalent in IE - Javascript

后端 未结 5 1489
太阳男子
太阳男子 2020-12-20 22:12

I have a javascript function to populate dropdowns for individual table rows like:

$scope.possibleOptions = getUniqueValues($scope.yypeOptions, \'yypeOption\         


        
5条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-12-20 22:46

    Your two syntaxes that you are asking about are the fat arrow for arrow functions and the spread operator. You can replace the former with a standard function expression and the latter with iteration using forEach that adds the elements to an array. In addition, you also need a replacement for the Set constructor that initializes it from an iterable. Instead, you need to add the elements one by one.

    You can write your function like this. This first adds all values into a set, and then gets the values from the list and back to a new array:

    function getUniqueValues(array, prop) {
        // create set
        var set = new Set();
        array.forEach(function (item) {
            set.add(item[prop]);
        });
    
        // convert set to array
        var result = [];
        set.forEach(function (item) {
            result.push(item);
        });
        return result;
    }
    

    Since there is basic support for Set, including forEach, in Internet Explorer 11, you can use this without a polyfill.

    Here is an example that runs fine in Internet Explorer 11:

    var options = [
        { yypeOption: "option1" },
        { yypeOption: "option2" },
        { yypeOption: "option1" },
        { yypeOption: "option1" },
        { yypeOption: "option3" },
    ];
    
    function getUniqueValues(array, prop) {
        var set = new Set();
        array.forEach(function (item) {
            set.add(item[prop]);
        });
        var result = [];
        set.forEach(function (item) {
            result.push(item);
        });
        return result;
    }
    
    console.log(getUniqueValues(options, 'yypeOption'));

提交回复
热议问题