數組操做-將嵌套數組變爲一維數組

 

Object.defineProperty() 方法會直接在一個對象上定義一個新屬性,或者修改一個對象的現有屬性, 並返回這個對象,因此用Object.defineProperty給Array添加一個flat()方法javascript

Object.defineProperty(Array.prototype, 'flat', {
    value: function(depth = 1) {
        return this.reduce(function (flat, toFlatten) {
            return flat.concat((Array.isArray(toFlatten) && (depth-1)) ? toFlatten.flat(depth-1) : toFlatten);
        }, []);
    }
});

let flatArr = [1, 2, [3, 4]].flat();

console.log(flatArr); //[1,2,3,4]

 還能夠傳入參數,有幾層嵌套就傳入幾java

 let flatArr2 = [1, 2, [3,  [4, 5] ] ].flat(2);this

 console.log(flatArr2) //[1 ,2, 3, 4, 5]prototype

相關文章
相關標籤/搜索