![](/img/trans.png)
[英]JavaScript Scope : please explain me why different result in and of loop creating variable
[英]can somene explain me, why this code result is different?(javascript object and array)
我会问这个:
我有一个像这样的javascript对象:
var stops = [
{"Geometry":{"Latitude":52.1615470947258,"Longitude":20.80514430999756}},
{"Geometry":{"Latitude":52.15991486090931,"Longitude":20.804049968719482}},
{"Geometry":{"Latitude":52.15772967999426,"Longitude":20.805788040161133}},
{"Geometry":{"Latitude":52.15586034371232,"Longitude":20.80460786819458}},
{"Geometry":{"Latitude":52.15923693975469,"Longitude":20.80113172531128}},
{"Geometry":{"Latitude":52.159849043774074, "Longitude":20.791990756988525}},
{"Geometry":{"Latitude":52.15986220720892,"Longitude":20.790467262268066}},
{"Geometry":{"Latitude":52.16202095784738,"Longitude":20.7806396484375}},
{"Geometry":{"Latitude":52.16088894313116,"Longitude":20.77737808227539}},
{"Geometry":{"Latitude":52.15255590234335,"Longitude":20.784244537353516}},
{"Geometry":{"Latitude":52.14747369312591,"Longitude":20.791218280792236}},
{"Geometry":{"Latitude":52.14963304460396,"Longitude":20.79387903213501}}
]
alert(stops);
在第一个代码中,警报结果是
我有一个来自ajax请求的数据,所以我可以使对象成为动态对象。我从数据库中调用它
var stops=new Array();
var myObject={};
$.ajax({
url: 'http://localhost:5566/Gps/api/rute.php?id='+id,
//url: 'http://localhost:5566/Gps/api/rute.php?id='+id,
dataType: 'jsonp',
jsonp: 'jsoncallback',
timeout: 5000,
async: false,
success: function(data, status){
i=0;
stops+="[";
$.each(data, function(i,item){
stops+="{\"Geometry\":{\"Latitude\":";
stops+=item.latitude;
stops+=",";
stops+="\"Longitude\":";
stops+=item.longitude;
stops+="}}";
stops+=",";
});
stops+=stops.substring(0,stops.length-1);
stops+="];";
alert(stops);
在第二个代码中,警报结果是
我认为Stops变量具有相同的结构,但是为什么警报结果不同? 我可以将第二个代码转换为类似于第一个代码的对象吗? 谢谢:)任何帮助将不胜感激
您的第一个对象是数组,第二个对象似乎是您手动将JSON字符串构建到数组中?
停止是一个数组,只需向其添加对象:
success: function(data, status){
$.each(data, function(i,item){
var stop = {
Geometry: {
Latitude: item.latitude,
Longitude: item.longitude
}
};
stops.push(stop);
});
alert(stops);
}
第二个是字符串。 是的,您可以解码JSON。
要将第一个转换为第二个使用:
JSON.stringify(stops);
要像第一次使用那样转换第二个:
JSON.parse(stops);
要么
$.parseJSON(stops);
编辑:根据建议,由于您使用的是jQuery,因此可以使用$ .parseJSON(stops)代替JSON.parse()。 如果可用,它将实际上使用本机解析。 没有等效的字符串(我知道)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.