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

使用JavaScript的map()方法处理URL参数生成指定格式请求地址

用map()生成多notes[]参数的URL方案

当然可以用map()来实现你要的效果,而且能完美生成符合需求的URL参数格式。

你原来的代码直接拼接数组会得到&notes[]=2,4,5这种不符合要求的格式,换成map()遍历生成每个参数片段再拼接就能解决问题。修改后的代码如下:

params.createdNotes = [2, 4, 5]

instance.fetchNotes = (params) => {
    let sortNotes = params.createdNotes.length === 0 
        ? '' 
        : params.createdNotes.map(note => `&notes[]=${note}`).join('');
    return instance.get(
        `/api/${params.section}&page=${params.currentPage}${sortNotes}`
    )
}

逻辑说明:

  • 当params.createdNotes为[2,4,5]时,map()会遍历数组每个元素,生成对应的参数片段数组['&notes[]=2', '&notes[]=4', '&notes[]=5']
  • 再通过join('')将数组元素拼接成完整的参数字符串&notes[]=2&notes[]=4&notes[]=5
  • 空数组的情况依然会返回空字符串,不会破坏URL结构

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 14:27:08