Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/372.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 使用getJSON(JQuery)和for.each从数组中获取第一个对象_Javascript_Foreach_Getjson - Fatal编程技术网

Javascript 使用getJSON(JQuery)和for.each从数组中获取第一个对象

Javascript 使用getJSON(JQuery)和for.each从数组中获取第一个对象,javascript,foreach,getjson,Javascript,Foreach,Getjson,现在,我将列出多个值,因为我将从for each循环中附加对象 $(document).ready(function(){ $.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=51.522035&lon=-0.105732",function(result){ $.each(result.weather, function(i,item){ $('#testfield').append('<p>

现在,我将列出多个值,因为我将从for each循环中附加对象

$(document).ready(function(){
$.getJSON("http://api.openweathermap.org/data/2.5/weather?lat=51.522035&lon=-0.105732",function(result){

  $.each(result.weather, function(i,item){
  $('#testfield').append('<p>' + item.main + '</p>');
  });

});
});

仅供参考:有时,天气提要提供多个weather.main。有时,只有一个。

如果要访问第一个元素,则只需执行该操作,而不是循环:

$('#testfield').append('<p>' + result.weather[0].main + '</p>');
//                                           ^^^
//                          access the first element in result.weather
$(“#testfield”).append(“”+result.weather[0].main+”

'); // ^^^ //访问result.weather中的第一个元素
$('#testfield').append('<p>' + result.weather[0].main + '</p>');
//                                           ^^^
//                          access the first element in result.weather