面试题答案
一键面试实现思路
- 首先检查浏览器是否支持
Array.prototype.flatMap
方法。 - 如果支持,直接使用原生方法,以获取最佳性能。
- 如果不支持,通过
Object.defineProperty
给Array.prototype
定义flatMap
方法,模拟其功能。在模拟实现中,先对数组的每个元素应用回调函数,然后将结果展平。
关键代码
if (!Array.prototype.flatMap) {
Object.defineProperty(Array.prototype, 'flatMap', {
value: function(callback, thisArg) {
return this.reduce((acc, val, index, array) => {
const mapped = callback.call(thisArg, val, index, array);
return acc.concat(Array.isArray(mapped)? mapped : [mapped]);
}, []);
},
writable: true,
configurable: true,
enumerable: false
});
}
在项目中使用 flatMap
时,无需额外处理,因为上述代码已确保无论浏览器是否支持原生 flatMap
,都能正常使用该方法。例如:
const arr = [1, 2, 3];
const result = arr.flatMap(num => [num * 2]);
console.log(result);