每天一个js算法 --- 数组扁平化
介绍
数组扁平化是指将多维数组或嵌套数组转换成一维数组的操作。在 JavaScript 中,你可以使用不同的方法来实现数组扁平化
直接上代码
Array.prototype.custom = function () { let flat = [] for (let item of this) { if (Array.isArray(item)) { flat = flat.concat(item.custom()) } else { flat.push(item) } } return flat } let arr = [[1, 2, 3, 4], [5, 6, 7], [8, 9, 10, 11, [12, 13, 14]], 15] console.log(arr); console.log(arr.custom());
- 这段代码首先是在Array的原型上增加一个custom方法首先定义一个空数组
- 用来保存扁平化之后的数组,先用for循环循环数组里面的数组,if判断里面用Array.isArray(item)这个方法是用来检查该item是否是一个数组,如果是的话,就调用flat.concat(item.custom()),这句里面concat方法,其实是用来拼接数组的,为什么拼接数组还要在调用一次item.custom()其实是防止数组里面还有数组,所以用了这个回调,再次检查是否item里面还有数组,然后再concat拼接数组,
- 如果前面Array.isArray(item)不满足他是一个数组的条件,直接调用flat.push方法,把item放到数组的后面,执行完了,返回该flat数组,就可以得到我们要的扁平化的数组了
扁平化前
扁平化后
大家如果喜欢可以关注我,我每天会发布一道前端的算法题,虽然写的不是很好,希望大家也可以指出错误,共同进步,祝大家秋招顺利
#24届秋招同行攻略分享#