Alternative or polyfill for Array.from on the Internet Explorer

前端 未结 5 2060
南方客
南方客 2020-11-27 18:12

I have a problem with my Angular App on the Internet Explorer. It runs everywhere without a problem (Chrome, Mozilla, Edge), but on on the IE.

I have analyzed with th

5条回答
  •  失恋的感觉
    2020-11-27 18:17

    I faced the same issue. Looked at the polyfill and it is threatening huge. Here is 2 lines short solution.

    The OP basically needs to create simple array from his array-like object. I used to my taste the most efficient 2 lines plain for loop (I had to make array from HTML DOM nodelist array-like object, same applicable to JavaScript arguments object).

    For the OP's case it could sound this way:

    var temp_array = [],
        length = tmp.length;
    
    for (var i = 0; i < length; i++) {
        temp_array.push(tmp[i]);
    }
    
    // Here you get the normal array "temp_array" containing all items
    // from your `tmp` Set.
    

    Make it separate function and you get 3 lines universal reusable solution for the IE<9 case.

    Here is how the separate function may look like:

    /**
     * @param arr The array | array-like data structure.
     * @param callback The function to process each element in the 'arr'.
     * The callback signature and usage is assumed similar to the 
     * native JS 'forEach' callback argument usage.
     */
    function customEach(arr, callback) {
        'use strict';
        var l = arr.length;
        for (var i = 0; i < l; i++) {
            callback(arr[i], i, arr);
        }
    };
    

    PS: here is the relevant description for forEach callback to see how to use the customEach callback.

提交回复
热议问题