gpt4 book ai didi

javascript - 解析 JSON 数据在第一个结果前面给出 "undefined"

转载 作者:行者123 更新时间:2023-11-28 11:23:45 25 4
gpt4 key购买 nike

我在解析邮政编码应用程序的 JSON 数据时遇到问题。以下代码无缘无故地在结果中抛出“未定义”:

“未定义16652、16654、16660”

var myZipcodes;
$.each(data, function(i, zipData){
if (zipData.zip){
myZipcodes += zipData.zip;
myZipcodes += ", ";
}
});
$('#results').html(myZipcodes);

这是我的对象的样子(第一个项目打开):

 [Object, Object, Object]
0: Object
city: "HUNTINGDON"
country: "US"
distance: "0"
lat: "40.49"
lng: "-78.01"
locationText: "Huntingdon, PA"
state: "PA"
zip: "16652"
__proto__: Object
1: Object
2: Object
length: 3
__proto__: Array[0]

我也尝试了 FOR 循环,但它给出了相同的结果:

var myZipcodes;
var length = data.length;
for (var i = 0; i < length; i++) {
myZipcodes += data[i].zip;
myZipcodes += ", ";
}

如果我尝试仅显示一个对象值的结果,它只会返回邮政编码,而不返回“未定义”。当我尝试迭代时,问题发生了。

最佳答案

原因是 myZipcodes 未初始化,并且很可能在实际使用前未定义。

var myZipcodes = '';  // <-- locally defined
// ... and initialised with ''
$.each(data, function(i, zipData) {
if (zipData.zip) {
myZipcodes += zipData.zip;
myZipcodes += ", ";
}
});

关于javascript - 解析 JSON 数据在第一个结果前面给出 "undefined",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22541862/

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