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

JavaScript中如何将单函数多次返回的字符串结果收集到同一数组

实现方案

可以将每次返回的字符串存入同一个数组,以下是两种常用的实现方式:

方案1:外层作用域声明数组(简单直接)

在example函数的外层作用域声明一个空数组,每次调用example时将参数e推入数组即可:

// 声明用于存储所有返回字符串的数组
const resultArr = [];

const example = e => {
  resultArr.push(e);
  console.log(e);
};

后续需要读取所有历史返回值时,直接访问resultArr即可。

方案2:闭包封装(避免污染全局作用域)

如果不想声明全局变量,可以用闭包把存储逻辑和数组封装起来,仅暴露必要的调用和读取方法:

const createExampleHandler = () => {
  // 私有数组,外部无法直接访问
  const resultArr = [];

  const example = e => {
    resultArr.push(e);
    console.log(e);
  };

  // 提供读取存储结果的方法,此处返回数组拷贝避免原数组被外部意外修改
  const getAllResults = () => [...resultArr];

  return { example, getAllResults };
};

// 使用示例
const { example, getAllResults } = createExampleHandler();

// 模拟多次API调用后执行example
example('string one');
example('string two');
example('string three');

// 获取所有存储的字符串
console.log(getAllResults()); // 输出:['string one', 'string two', 'string three']

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.28 02:45:03