swa*_*gyP 7 javascript flatten
我正在尝试编写一个函数来展平数组.我有部分功能正常工作,另一半我需要帮助.
flatten: function(anyArray, singleLevel) {
if (singleLevel == true) {
flatArray = Array.prototype.concat.apply([], anyArray);
return flatArray;
}
flatArray = Array.prototype.concat.apply([], anyArray);
if (flatArray.length != anyArray.length) {
flatArray = someObject.array.flatten(flatArray);
}
return flatArray;
}
Run Code Online (Sandbox Code Playgroud)
如果我打字
.flatten([[[1],[1,2,3,[4,5],4],[2,3]]], true);
Run Code Online (Sandbox Code Playgroud)
我希望它只展平一个级别:
[[1],[1,2,3,[4,5],4],[2,3]]
Run Code Online (Sandbox Code Playgroud)
现代 JavaScript 允许我们使用各种技术轻松处理这个问题
使用Array.prototype.flat-
const arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
const flatArr =
arr.flat(1) // 1 is default depth
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]Run Code Online (Sandbox Code Playgroud)
使用Array.prototype.flatMap-
const arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
const flatArr =
arr.flatMap(x => x)
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]Run Code Online (Sandbox Code Playgroud)
使用传播参数 Array.prototype.concat
const arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
const flatArr =
[].concat(...arr)
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]Run Code Online (Sandbox Code Playgroud)
较旧版本的 JavaScript(ECMAScript 5 及以下)可以使用以下技术Function.prototype.apply-
var arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
var flatArr =
Array.prototype.concat.apply([], arr)
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]Run Code Online (Sandbox Code Playgroud)
使用Array.prototype.reduce-
var arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
var flatArr =
arr.reduce((r, a) => r.concat(a), [])
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]Run Code Online (Sandbox Code Playgroud)
使用原始for循环 -
var arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
var flatArr =
[]
for (var i = 0; i < arr.length; i = i + 1)
flatArr = flatArr.concat(arr[i])
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]Run Code Online (Sandbox Code Playgroud)
的concat阵列方法期望一个或多个阵列作为参数,其元素将被附加:
[1].concat([2, 3], [4]) // [1, 2, 3, 4]
Run Code Online (Sandbox Code Playgroud)
因此,如果您使用apply,那将使另一个层次变得平坦:
[].concat.apply([1], [[2], [3]]) // === [1].concat([2], [3])
Run Code Online (Sandbox Code Playgroud)
因此,您可以使用push代替concat,或者call(或者直接调用)代替apply仅获得一个展平级别。