【问题标题】:Array from API returns empty when using methods使用方法时来自 API 的数组返回空
【发布时间】:2026-01-19 10:50:01
【问题描述】:

我从 API 接收一个数字数组,但是当我对其使用方法时,该数组返回空。

当我记录一个示例数组和 API 数组时,两者的格式不同(见下图)

第二个数组来自长度为 20 的 API,当我尝试将其切片为 3 时,它以相同的格式返回但为空。

扩展日志时的示例数组和 API 数组如下所示

当我尝试使用以下方法对它们进行切片时:

exampleArr.slice(0,3)
apiArr.slice(0,3)

他们记录以下内容

任何帮助将不胜感激。

【问题讨论】:

标签: javascript arrays methods slice


【解决方案1】:

您的代码是正确的,但我认为您在初始加载页面上的数组是空的,在获得 API 的响应后,您应该使用Promise 或等待setTimeout 的响应。

    return new Promise(
         function (resolve, reject) {
          ////////////////Your APi/////////
          axios.get('/sample', (response)=>{
       if(response.state === 'success')
           ////// Do slice on array ////
           let doSlice = apiArr.slice(0,3);
           resolve(apiArr.slice(0,3)); // resolve
         } else {
           reject(reason); // reject
         }
      })
      )

或者

  setTimeout(function(){
     apiArr.slice(0,3);
  },1000)

【讨论】:

    【解决方案2】:

    当我记录示例数组和 API 数组时,两者的格式不同

    它们具有相同的格式。你的“二”只是一个空数组。

    【讨论】: