方法一、采用forEach方法进行数组扁平化
这种方法只能扁平化二维数组
let arr = ['1', 'a', 'v', [4, 7, 3], ['ok', 'yes']]; // 原数组
let newArr = []; // 创建一个新数组
arr.forEach(item => {
if (typeof item == 'object') { // 判断item是不是大数组中的小数组
for (let smallItem of item) { // 把小数组中的元素进行遍历添加到新数组中
newArr.push(smallItem);
}
}else {
newArr.push(item); // 将大数组中原本就是字符砖的元素直接添加到新数组中
}
})
console.log(newArr);
方法二、用 concat 直接将原数组当中的元素 合并起来 形成新数组
这种方法只能扁平化二维数组
let arr = ['1', 'a', 'v', [4, 7, 3], ['ok', 'yes']]; // 原数组
let newArr = []; // 创建一个新数组
// 用 concat 直接将原数组当中的元素 合并起来 形成新数组
for (let item of arr) { // 对大数组进行遍历
newArr = newArr.concat(item)
}
console.log(newArr);
方法三、ES6 新增 数组扁平化方法 flat()
let arrTwo = ['1', 'a', 'v', [4, 7, 3], ['ok', 'yes']]; // 原数组
let arrOne = ['1', 'a', 'v', [4, 7, ['zbc', 'obj'], 3], ['ok', 'yes']]; // 原数组
// 默认只展开(处理)一层数组
console.log(arrOne.flat());
// 需要展开多层数组时 直接在括号里添加层数的数字
console.log(arrTwo.flat(3));
var arrThree = ['a', 'b', ['c', 'd', ['s', [123, 456]]], 'e', ['f']];
// 不确定有多少层数组时 直接 添加 Infinity 表示无穷的意思 任何层数组都可以展开
console.log(arrTwo.flat(Infinity));