使用方法时API的数组返回空

时间:2018-09-24 14:31:38

标签: javascript arrays methods slice

我正在从API接收数字数组,但是当我在其上使用方法时,该数组返回空值。

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

two array with different content

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

示例数组和API数组在展开时会记录如下内容

The example array and API array when expanded

当我尝试使用以下方法切片时:

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

他们记录以下内容

Array when slice apply

任何帮助将不胜感激。

2 个答案:

答案 0 :(得分:1)

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

    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)

答案 1 :(得分:0)

  

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

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