gpt4 book ai didi

javascript - json 数组可能时不时会丢失一个项目,如何将其设置为 0 并继续。也许是 isnull ?

转载 作者:行者123 更新时间:2023-12-03 05:09:33 25 4
gpt4 key购买 nike

在我使用的天气数组中,只有下雨时才会出现雨。如果某个字段不在数组中,我该如何跳过该字段并继续前进?

$.ajax({
type: 'GET',
url: "http://api.openweathermap.org/data/2.5/forecast?lat="+latitude+"&lon="+longitude+"&units=imperial&APPID=removed",
success: function(response) {
icon = "wi-day-"+response.list[0].weather[0].main.toLowerCase();
$('#city').html(response.city.name);
$('#country').html(response.city.country);
$('#current_temp').html(Math.round(response.list[0].main.temp)+' ºF');
$('#weather_description').html(response.list[0].weather[0].description);
$('#weather').html(response.list[0].weather[0].main);
$('#max_temp').html(Math.round(response.list[0].main.temp_max)+' F');
$('#min_temp').html(Math.round(response.list[0].main.temp_min)+' F');
$('#humidity').html(response.list[0].main.humidity+' %');
$('#rain_volume').html(response.list[0].rain[3h]+'"');
$('#wind_speed').html(response.list[0].wind.speed+'MPH');

console.log(response);
}

});

我正在谈论的线路

 $('#rain_volume').html(response.list[0].rain[3h]+'"');

最佳答案

这只是一个避免所有 if 检查的示例。我个人不会使用它。但这只是一个想法

function always(obj){
return new Proxy(obj, {
get(target, prop) {
if(target.hasOwnProperty(prop) && typeof target[prop] !== 'object'){
return target[prop];
}
return always(target[prop] || {[Symbol.toPrimitive]:() => ''});
}
});
}
let response = {}; // some response
response = always(response);

// this line will not throw any error and will print an empty line
console.log(response.list[0].rain["3h"]+"");

response = {list:[{rain:{"3h":"test"}}]}; // some response
response = always(response);

// this line should print 'test'
console.log(response.list[0].rain["3h"]+"");

关于javascript - json 数组可能时不时会丢失一个项目,如何将其设置为 0 并继续。也许是 isnull ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41878856/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com