【问题标题】:Concat results of single function in JavaScriptJavaScript中单个函数的Concat结果
【发布时间】:2021-12-19 13:41:32
【问题描述】:
const example = e => {
        console.log(e);
    };

每次进行 API 调用时,example() 或更确切地说是e 都会返回不同的字符串,例如:

string one string two string three

有没有办法将所有这些字符串连接到一个数组中?

【问题讨论】:

  • let arr = []; const example = str => { arr.push(str) }; 不要调用 var e - 大多数人都将它用于事件,就像我们将 i 用于索引一样
  • 有。只需 push 到一个数组,然后你可以在你认为合适的时候连接数组。

标签: javascript arrays reactjs javascript-objects


【解决方案1】:

只需在某处声明一个数组并将值推送到那里。

let arr = [];
const example = item => {
        arr.push(item);
        console.log(arr);
    };

【讨论】:

    【解决方案2】:
    let arr = [];
    const example = e => {
      arr.push(e);
      console.log(e);
    };
    

    【讨论】:

      【解决方案3】:

      首先,我建议使用发送请求的函数,例如sendRequest()。如果您访问数据库或某些网站,则必须声明 async 函数,因为它不确定,当您收到回复时。然后,无论 api 调用是否成功,您的 sendRequest 函数都可以返回一个 javascript 对象。关键字 await 等待,直到 promise 被解决。

      现在回答您的问题:如果您的调用成功,只需将您的结果推送到外部定义的数组apiResults,就是这样。

      const apiResults = [];
      
      async function sendRequest() {
        try {
          const apiResult = await axios.get('https://jsonplaceholder.typicode.com/todos/1');
          const apiSuccess = Boolean(apiResult);
          
          if (apiSuccess) {
            apiResults.push(apiResult);
          }
          return { ok: apiSuccess, data: apiResult }; 
        } catch (err) {
          return { ok: false, data: {} };
        }
      }
      
      (async function test() {
        console.log('Before', apiResults);
        const response = await sendRequest();
        console.log('After', apiResults);
      })();
      <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2018-10-11
        • 1970-01-01
        • 2012-08-10
        • 2012-09-10
        • 2016-12-08
        • 1970-01-01
        • 2021-11-01
        相关资源
        最近更新 更多