繁体   English   中英

JSON对象不会使用Ajax转移到js数组中

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM