Javascript Jquery无法访问循环外部的数组
我从下面的代码中得到一个奇怪的行为。以下代码来自ajaxsuccess、和Javascript Jquery无法访问循环外部的数组,javascript,jquery,arrays,loops,Javascript,Jquery,Arrays,Loops,我从下面的代码中得到一个奇怪的行为。以下代码来自ajaxsuccess、和console.log(positions)内部循环工作正常,但外部循环什么都没有。 success: function (data) { var positions = []; $.each(data, function (index, value) { $.each(value, function (index1, value1) { positions.pus
console.log(positions)代码>内部循环工作正常,但外部循环什么都没有。
success: function (data) {
var positions = [];
$.each(data, function (index, value) {
$.each(value, function (index1, value1) {
positions.push({
lat: value1.rider_location.lat,
lng: value1.rider_location.lng,
});
//This works fine | I can get the results. But after commenting out the below line then the last `console.log(positions)` doesn't shows anything.
console.log(positions);
});
});
console.log(positions);
}
Ajax中的数据
给出了以下结果,然后我循环遍历它并将值分配给位置
在回路内部,我得到以下结果:
并且在循环的外部
控制台。log(positions)
不会给出任何异常,也不会给出任何结果。鉴于返回的数据格式,我会尝试:
success: function (data) {
var positions = [];
$.each(data, function (index, value) {
$.each(value, function (index1, value1) {
positions.push({
lat: value1.rider_location.lat,
lng: value1.rider_location.lng,
});
//This works fine | I can get the results. But after commenting out the below line then the last `console.log(positions)` doesn't shows anything.
console.log(positions);
});
});
console.log(positions);
}
似乎您正试图使用第二个循环循环rider_location,但rider_location是一个对象,所以您可以访问它的属性
success: function (data) {
var positions = [];
$.each(data.riders, function (index, value) {
positions.push({
lat: value.rider_location.lat,
lng: value.rider_location.lng,
});
});
console.log(positions);
}
PS请随时告诉我:)您的数据不是数组,而是对象。在其上使用
$。each()
意味着它将在其所有属性上循环,这就是为什么它不能按预期工作的原因。您可能想循环查看data.riders
。此外,没有其他数组可循环,因此第二个循环不应存在:
var数据={
乘客:[{
驾驶室位置:{
拉丁语:2,
液化天然气:3
}
},
{
驾驶室位置:{
拉丁语:4,
液化天然气:5
}
}
]
};
var头寸=[];
$.each(data.riders,函数(索引,值){
位置,推({
lat:value.rider\u location.lat,
液化天然气:value.u location.lng,
});
});
控制台日志(位置)代码>
它不提供任何异常,因为您声明了一个空的位置,所以当您记录它时,它将打印该位置。您的数据
或值
很可能为空。尝试将这些记录在循环中。似乎数据
或值
是一个空集合。您能显示这些代码的填充位置吗?您正试图在哪里使用console.log(positions)
?在成功内部:
(如问题中所示)还是在其他地方?(即外部成功:函数(数据){
)?感谢您更新问题。您能在问题中的代码片段中重新创建问题吗?您提供的代码没有问题。我怀疑您已经有过,但已经阅读过。我只能猜测您正在尝试访问成功:
回调之外的位置(甚至可能在ajax调用开始之前),但这不是问题代码中的内容,两个独立的fiddle已经证明它工作正常。uncaughttypeerror:无法读取未定义的属性“lat”
try console.log(value)和console.log(value.rider\u位置),看看你是否得到了正确的结果。