[英]JSON objects wont transfer into js array using ajax
我尝试进行console.log记录时得到未定义
var farr = [];
$.ajax({
url: "https://whispering-cliffs-33347.herokuapp.com/employees",
type: "GET",
contentType: "application/jsonp"
}).done(function(employees) {
for(let i in employees){
farr.push(employees[i]);
}
})
console.log(farr[8]);
有任何想法吗?
console.log(farr[8]);
将会在响应可用之前执行。因此,首先done
推送本地数组中的所有元素,然后在下一次done
日志中done
该值
var farr = [];
$.ajax({
url: "https://whispering-cliffs-33347.herokuapp.com/employees",
type: "GET",
contentType: "application/jsonp"
}).done(function(employees) {
employees.forEach(function(item){
farr.push(item)
})
}).done(function(elem){
console.log(farr[8]);
})
您不能使用标准的for循环来迭代对象。 为了做到这一点,您应该首先在数组中获取对象键并对其进行迭代。
const keys = Object.keys(employees);
keys.forEach((i) => {
farr.push(employees[i]);
}
console.log(farr[8]);. // You should put this in the call back itself
或者,您可以使用lodash的forEach直接迭代对象。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.