Typescript中如何正确嵌套使用展开运算符实现二维数组扁平化?
你写的代码报错是因为展开运算符...不能单独作为箭头函数的返回值使用,它只能在数组字面量、对象字面量、函数参数列表这三类场景中使用。
下面是几种可行的实现方案:
方案1:使用flatMap(推荐)
flatMap是map和flat的组合语法,专门用于处理「map返回数组,需要将结果扁平化为一维数组」的场景,代码最简洁:
const myFruits = ['apple', 'grapefruit', 'pear'].flatMap(fruit => [ fruit, 'red ' + fruit ]) console.log(myFruits) // ["apple", "red apple", "grapefruit", "red grapefruit", "pear", "red pear"]
方案2:map后调用flat扁平化
如果你已经写好了原来的map逻辑,只需要在map之后调用flat()方法打平数组即可:
let myFruits = [ ...(['apple', 'grapefruit', 'pear'].map((fruit) => [ fruit, 'red ' + fruit, ] ).flat()) ]
方案3:使用reduce实现(兼容旧环境)
如果运行环境不支持ES2019新增的flat、flatMap方法,可以用reduce实现:
const myFruits = ['apple', 'grapefruit', 'pear'].reduce((result, fruit) => { result.push(fruit, 'red ' + fruit) return result }, [])
内容的提问来源于stack exchange,提问作者Ibrahim Ali
相关产品推荐
相关产品推荐

