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

如何将JavaScript对象数组转换为带有序列表的指定格式字符串?

实现方法

可以通过以下方式生成你需要的格式:

修改后的代码直接输出目标格式内容:

let arr = [
            {
              'message': "message 1",
              'date': "date 1",
              'text': "text 1"
            },
            {
              'message': "message 2",
              'date': "date 2",
              'text': "text 2"
            },
            {
              'message': "message 3",
              'date': "date 3",
              'text': "text 3"
            },
          ];

// 生成带序号和缩进的列表项
const listItems = arr.map((item, index) => `    ${index + 1}. ${item.message} at ${item.date}`).join('\n');
// 拼接前置文本与列表内容
const output = `The following messages:\n${listItems}`;

console.log(output);

代码说明

  • 用map遍历数组,借助第二个参数index生成从1开始的序号,每个列表项前加4个空格实现缩进
  • 通过join('\n')把所有列表项用换行符连接成完整的列表字符串
  • 最后将前置文本和列表字符串拼接,中间用换行符分隔,即可得到你需要的输出格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 04:25:41