我创建了一个ajax调用,并且将ajax成功数据保存在一个数组中,当我执行console
时,我在ajax之外调用该数据。我的数组,它正在返回数组,这是屏幕截图:
这是我的代码:
function getData(){
let surahArray = [];
// created empty variable
$.ajax({
url: 'http://mp3quran.net/api/_english.php',
type: 'get',
success: function(data){
let urlServer = data.reciters[112].Server;
let resUrl;
for(resUrl=1; resUrl <= 114; resUrl++){
resUrl = resUrl < 10 ? '00' + resUrl : '' + resUrl;
resUrl = (resUrl < 100 && resUrl > 9) ? '0' + resUrl : '' + resUrl;
surahArray.push(urlServer + '/' + resUrl + '.mp3');
// pushing array data to that empty array
}
},
error: function(err){
console.log(err);
}
});
let surahs = surahArray;
// working
console.log(surahs);
// not working
console.log(surahs[0]);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<button onclick="getData()">Get Data</button>
如果我这样做console.log(surahs)
它返回了我的数组列表,但是当我这样做时 console.log(surahs[0])
,它正在返回我undefined
在console
.
请帮帮我,我哪里错了?
最佳答案
您应该仅在 HTTP 请求完成后使用您的变量 (surahs)。
您所遇到的情况是,当您在浏览器控制台中展开数组时,console.log 会再次读取数组(以下是有关此问题的更多详细信息: console.log() shows the changed value of a variable before the value actually changes )
function useMyData(data) {
console.log(data);
}
$.ajax({
url: 'http://mp3quran.net/api/_english.php',
type: 'get',
success: function(data){
let urlServer = data.reciters[112].Server;
let resUrl;
for(resUrl=1; resUrl <= 114; resUrl++){
resUrl = resUrl < 10 ? '00' + resUrl : '' + resUrl;
resUrl = (resUrl < 100 && resUrl > 9) ? '0' + resUrl : '' + resUrl;
surahArray.push(urlServer + '/' + resUrl + '.mp3');
// pushing array data to that empty array
}
// use it here
useMyData(surahArray);
},
error: function(err){
console.log(err);
}
});
关于javascript - 未获取数组的值,但数组存在 - JS,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60559103/