当前位置: 首页 > 工具软件 > Flat > 使用案例 >

js 实现flat函数

仇睿
2023-12-01
  let arr = [1, 2, [
            [3, 4],
            [5, 6]
        ]];
        const checkType = function(arr) {
            return Object.prototype.toString.call(arr).slice(8, -1)
        }

        Array.prototype.myFlat = function(num) {
            let type = checkType(arr)
            let result = []
            if (!Object.is(type, 'Array')) {
                return
            }

            this.forEach(item => {
                let cellType = checkType(item)
                if (Object.is(cellType, 'Array')) {
                    num--
                    if (num < 0) {
                        let newArr = result.push(item)
                        return newArr
                    }
                    result.push(...item.myFlat(num))
                } else {
                    result.push(item)
                }

            });
            return result
        }
        console.time();
        console.log(arr.myFlat(Infinity));
        console.timeEnd();
function myFlat(arr) {
            let result = []
            for (let i = 0, len = arr.length; i < len; i++) {
                if (Array.isArray(arr[i])) {
                    result = result.concat(myFlat(arr[i]))
                } else {
                    result.push(arr[i])
                }
            }
            return result
        }
        console.log(myFlat(arr));

//ES6 

function myFlat(arr) {
            while (arr.some(item => Array.isArray(item))) {
                arr = [].concat(...arr)
            }
            return arr
        }
        console.log(myFlat(arr));

 类似资料: