我从 API 接收到一个数字数组,但是当我对其使用方法时,该数组返回空。
当我记录一个示例数组和 API 数组时,两者具有不同的格式(见下图)
第二个数组来自长度为 20 的 API,当我尝试将其切片为 3 时,它以相同的格式返回但为空。
扩展后的示例数组和 API 数组如下所示
当我尝试使用以下方式对它们进行切片时:
exampleArr.slice(0,3)
apiArr.slice(0,3)
他们记录关注
如有任何帮助,我们将不胜感激。
最佳答案
你的代码是正确的,但我认为你在初始加载页面上的数组是空的,在得到 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)
关于javascript - 使用方法时,来自 API 的数组返回空,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52481635/