You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用fp-ts实现数组中指定元素的替换操作

实现方案

可以使用 fp-ts Array 模块提供的 updateAt 方法完成指定索引位置的元素替换,符合你现有代码逻辑的完整实现如下:

import { pipe } from 'fp-ts/function'
import * as A from 'fp-ts/Array'
import * as O from 'fp-ts/Option'

const animals = ['monkey','cat','lion']

const result = pipe(
    animals,
    A.findIndex((animal)=> animal === 'cat'),
    O.matchW(
      () => animals,
      (index) => pipe(
        animals,
        A.updateAt(index, 'dog'),
        // 此处index已经通过findIndex校验存在,getOrElse仅做类型安全兜底
        O.getOrElse(() => animals)
      )
    )
  )

// 输出结果: ['monkey','dog','lion']

如果你的需求是替换数组中所有值为cat的元素,可以直接使用更简洁的map方案,不需要提前查找索引:

const result = pipe(
  animals,
  A.map(animal => animal === 'cat' ? 'dog' : animal)
)

两种方案的差异:

  • 第一种方案仅替换第一个匹配到的cat,和你原有代码逻辑一致
  • 第二种方案会替换数组中所有等于cat的元素,适合批量替换场景

内容的提问来源于stack exchange,提问作者Jonathan Southern

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 12:27:04