数组扁平化:多维数组变一维数组。
方式1: ES6中的flat函数
let arr = [1,2,3,[4,5,6,[7,9,8]]]; console.log( arr.flat( Infinity ) );
方式2:扩展运算符
var arr = [1,2,3,[4,5,6,[7,9,8]]]; function flatten(arr) { while (arr.some(item => Array.isArray(item))) { arr = [].concat(...arr); } return arr; } console.log(flatten(arr))
方式3:递归加for循环
Array.prototype.flatten = function () { var newArr = []; for (var i = 0; i < this.length; i ++) { if (Array.isArray(this[i])) { newArr = newArr.concat(this[i].flatten()); } else { newArr.push(this[i]); } } return newArr; } var arr=[1,2,3,[4,5,6,[7,9,8]]] console.log(arr.flatten())
原文链接: https://blog.csdn.net/weixin_44499870/article/details/116571351?spm=1001.2014.3001.5502
标签:arr,console,扁平化,newArr,flatten,数组,var From: https://www.cnblogs.com/yunyin/p/16723857.html