首先上几个面试题:(真难)
1. 手写函数实现数组扁平化(只减少一级嵌套)
思路:
function flatten(arr) {let res = [];arr.forEach((item) => {if (Array.isArray(item)) {item.forEach((e) => res.push(e));} else {res.push(item);}});return res;}console.log(flatten2([1, [2, [3]], 4]));function flatten2(arr) {let res = [];arr.forEach((item) => {res = res.concat(item);});return res;}
实现数组深度扁平化:
// 深度拍平function flattenDeep1(arr) {let res = [];arr.forEach((item) => {if (Array.isArray(item)) {let flatItem = flattenDeep1(item);flatItem.forEach((e) => res.push(e));} else {res.push(item);}});return res;}function flattenDeep2(arr) {let res = [];arr.forEach((item) => {if (Array.isArray(item)) {let flatArr = flattenDeep2(item);res = res.concat(flatArr);} else {res = res.concat(item);}});return res;}
2. 手写代码表示 new 的过程