.flat() is not a function, what's wrong?

前端 未结 5 1583
情话喂你
情话喂你 2020-12-16 08:40

The following code

function steamrollArray(arr) {
  // I\'m a steamroller, baby
  return arr.flat();
}

steamrollArray([1, [2], [3, [[4]]]]);
5条回答
  •  無奈伤痛
    2020-12-16 09:44

    Array.flat is not supported by your browser. Below are two ways to implement it.

    As a function, the depth variable specifies how deep the input array structure should be flattened (defaults to 1; use Infinity to go as deep as it gets) while the stack is the flattened array, passed by reference on recursive calls and eventually returned.

    function flat(input, depth = 1, stack = [])
    {
        for (let item of input)
        {
            if (item instanceof Array && depth > 0)
            {
                flat(item, depth - 1, stack);
            }
            else {
                stack.push(item);
            }
        }
        
        return stack;
    }
    

    As a Polyfill, extending Array.prototype if you prefer the arr.flat() syntax:

    if (!Array.prototype.flat)
    {
        Object.defineProperty(Array.prototype, 'flat',
        {
            value: function(depth = 1, stack = [])
            {
                for (let item of this)
                {
                    if (item instanceof Array && depth > 0)
                    {
                        item.flat(depth - 1, stack);
                    }
                    else {
                        stack.push(item);
                    }
                }
                
                return stack;
            }
        });
    }
    

提交回复
热议问题