// Array.prototype.flatMap ES2020// flat + mapconst arr = ["123", "456", "789"];const newArr = arr.map(function (item) { console.log(item.split('')); return item.split('')});console.log(newArr.flat());//[1,2,3,4,5,6,7,8,9];// 遍历 扁平化// map - > flat// 效率要高一点// 返回值是一个心的数组。const newArr2 = arr.flatMap(function (item) { return item.split('');})console.log(newArr2);//[1,2,3,4,5,6,7,8,9];// item -> 当前遍历的元素// 当前遍历的元素在数组中对应的下标// arr 当前数组// 回调函数中的this 默认指向window// 严格模式下 this 为 undefined// flatMap 的第二个参数可以改为回调函数内this 的指向const newArr3 = arr.flatMap(function (item,idx,arr) {})Array.prototype.myFlatMap = function (cb) { if (typeof cb !== 'function') { throw new TypeError('CallBack must be function'); } // cb(1, 2, 3); var arg2 = arguments[1], arr = this, len = arr.length, item, idx = 0, res = []; while (idx < len) { item = arr[idx];// 浅拷贝。 res.push(cb.apply(arg2, [item, idx, arr])); idx ++; } return res;}