【问题标题】:How do i use spread operator over spread operator | Typescript我如何使用扩展运算符而不是扩展运算符 |打字稿
【发布时间】:2021-09-09 04:33:01
【问题描述】:

我不确定我这样做是否正确(让我知道).. 让我们说

let myFruits = [
    ...(['apple', 'grapefruit', 'pear'].map((fruit) =>
        [
            fruit,
            'red ' + fruit,
        ]
    ))
]

console.log(myFruits) //[["apple", "red apple"], ["grapefruit", "red grapefruit"], ["pear", "red pear"]]

我想要的是

["apple", "red apple", "grapefruit", "red grapefruit", "pear", "red pear"]

我试着做...(它给出了一个错误)

let myFruits = [
    ...(['apple', 'grapefruit', 'pear'].map((fruit) =>
        [
            fruit,
            'red ' + fruit,
        ]
    )).map((fr)=>...fr)
]

【问题讨论】:

  • 你不想要传播运算符;改用flatMap 函数(flatMap 是 JS 的等价于 Linq 的SelectMany)。
  • 这里包含一堆解决方法,适用于您的环境不支持flatMapWhy no Array.prototype.flatMap in javascript?(在 JS 中,它仅在最近才可用)。
  • 或者,使用flatMap 只是map 后跟flatten 的事实,并使用[].concat(...lists) 代替lists.flatten()。在您的情况下,它类似于[].concat(...(['foo', 'bar'].map(x => [x, 'red ' + x]))

标签: typescript


【解决方案1】:

使用reduce:

const FRUITS = ['apple', 'grapefruit', 'pear']

const result = FRUITS.reduce<string[]>(
    (acc, elem) => [...acc, elem, `red ${elem}`], []
)

【讨论】:

    猜你喜欢
    • 2018-07-25
    • 2017-12-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-16
    • 2019-09-26
    相关资源
    最近更新 更多