想到这个属性的是出至一个题,二维数值取值都好取:
let arr = [
[10, 20],
[20, 40],
[40, 100],
[100, 200]
] // 二维
let t = arr.reduce(function(temp, item) {
return temp.concat(item)
})
console.log(t);
但如果是多维数组且还不知道里面到底有多少维如何解决?
//多维?
let newarr=[10,20,30,[[30]],[[[[[100]]]]]];
flat():
这个时候就用到了flat();flat()是JavaScript中一个数组方法,用于将嵌套数组转换为单层数组。这个方法可以通过一个可选参数depth来指定展开的层数,默认为1。
语法格式:
flat();
flat(depth);//可选参数
返回值:
flat()的返回值是一个新的数组,其中包含拼接后的子数组元素。
描述:
flat()
方法属于复制方法。它不会改变 this
数组,而是返回一个浅拷贝,该浅拷贝包含了原始数组中相同的元素。
如果待展开的数组是稀疏的,flat()
方法会忽略其中的空槽。例如,如果 depth
是 1,那么根数组和第一层嵌套数组中的空槽都会被忽略,但在更深的嵌套数组中的空槽则会与这些数组一起保留。
flat()
方法是通用的。它只需要 this
值具有 length
属性和整数键属性即可。但是,如果要展开元素,则它们必须是数组。
实例:
flat()可以展平所嵌套的数组;
const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
在稀疏数组上使用flat():
flat()作用则是删除数组中逗号之间的空槽:
const arr5 = [1, 2, , 4, 5];
console.log(arr5.flat()); // [1, 2, 4, 5]
const array = [1, , 3, ["a", , "c"]];
console.log(array.flat()); // [ 1, 3, "a", "c" ]
const array2 = [1, , 3, ["a", , ["d", , "e"]]];
console.log(array2.flat()); // [ 1, 3, "a", ["d", 空, "e"] ]
console.log(array2.flat(2)); // [ 1, 3, "a", "d", "e"]
在非对象数组上使用flat();
flat()
方法读取 this
的 length
属性,然后访问每个整数索引。如果元素不是数组,则直接将其附加到结果中。如果元素是数组,则根据 depth
参数进行展开操作。
const arrayLike = {
length: 3,
0: [1, 2],
// 嵌套的类数组对象不会被展平
1: { length: 2, 0: 3, 1: 4 },
2: 5,
};
console.log(Array.prototype.flat.call(arrayLike));
// [ 1, 2, { '0': 3, '1': 4, length: 2 }, 5 ]
多维问题解决:
参数值为Infinity无论所写数组或非数组有多少维都会解出成一维
let newarr=[10,20,30,[[30]],[[[[[100]]]]]];
function fn(newarr) {
newarr.flat(Infinity);
};
console.log(fn(newarr));
//[10, 20, 30, 30, 100]