只是要在安全方面,你应该总是检查任意键的在for in
循环业主:
for (var i in PriceRanges[purpose])
{
if (PriceRanges[purpose].hasOwnProperty(i))
{
html += '<option value="' + PriceRanges[purpose][i].id + '">'
+ PriceRanges[purpose][i].text + '</option>';
}
}
但这看起来我喜欢你遍历数组,在这种情况下:使用for
,不for in
,因为在for in
最后i
阵列上会length属性...
for (var i=0;i<PriceRanges[purpose].length;i++)
{
html += '<option value="' + PriceRanges[purpose][i].id + '">'
+ PriceRanges[purpose][i].text + '</option>';
}
当然,要格外,超级骗子安全,你应该如果添加一个到两个循环:
if (PriceRanges[purpose][i].id && PriceRanges[purpose][i].text)
为了避免使用不存在的属性(并因此将返回undefined)
你可以把你的JSON对象吗?我们需要查看属性 –
请控制'PriceRange [purpose]'并发布对象内容。 – David
'PriceRanges [purpose]是一个数组还是一个对象?很有可能你得到的'r'值不是你期望的类型,所以'r.text'是'undefined'。这可能是因为“i”的一个值不符合你的期望。如果'PriceRanges [purpose]'是一个数组,那么你应该用'for(var i = 0,len = PriceRanges [purpose] .length; i
jfriend00