如何在for循环的if语句中判断Source键是否为空?
问题分析与修正
你的代码没有输出,核心问题是判断条件完全错误,同时存在逻辑混淆:
- 你要判断的是当前遍历的
uniqueFeatures[i].properties里的Source字段是否有有效值,但原代码错误地去访问listContent[Source].properties——而listContent是用来拼接HTML的字符串,根本不是对象,这么写会直接抛出错误,导致循环内代码完全不执行。 Source作为属性名,需要用字符串引号包裹,否则会被当作未定义的变量处理。
正确的判断逻辑
要判断Source键是否存在且有有效值,需要针对当前循环项的properties对象做检查,常用的严谨判断方式有两种:
方式1:检查是否为空值(空字符串、null、undefined都视为无有效值)
if (!uniqueFeatures[i].properties.Source) { // Source无有效值时的逻辑 }
方式2:更精准的检查(仅当Source是空字符串或未定义时视为无有效值)
if (uniqueFeatures[i].properties.Source === "" || typeof uniqueFeatures[i].properties.Source === 'undefined') { // Source为空或未定义时的逻辑 }
修正后的完整代码
if (visibleFeatures) { var uniqueFeatures = getUniqueFeatures(visibleFeatures, "arrayIndex"); // 先初始化listContent为空字符串,避免拼接时出现undefined前缀 var listContent = ''; for (var i = 0; i < uniqueFeatures.length; i++) { // 针对当前循环项的Source做判断 if (!uniqueFeatures[i].properties.Source) { listContent += '<div class="dealer"><h3><a href="' + uniqueFeatures[i].properties.arrayIndex + '" class="location-heading">' + uniqueFeatures[i].properties.Name + '</a></h3><p class="address">' + uniqueFeatures[i].properties.Address + '<br>' + uniqueFeatures[i].properties.City + ', ' + uniqueFeatures[i].properties.State + ' ' + uniqueFeatures[i].properties.Zip + '</p><p class="phone"><a href="tel:+1' + uniqueFeatures[i].properties.Phone + '">' + uniqueFeatures[i].properties.Phone + '</a></p></div>'; } else { listContent += '<div class="dealer"><h3><a href="' + uniqueFeatures[i].properties.arrayIndex + '" class="location-heading">' + uniqueFeatures[i].properties.Name + '</a></h3><p class="address">' + uniqueFeatures[i].properties.Address + '<br>' + uniqueFeatures[i].properties.City + ', ' + uniqueFeatures[i].properties.State + ' ' + uniqueFeatures[i].properties.Zip + '</p><p class="phone"><a href="tel:+1' + uniqueFeatures[i].properties.Phone + '">' + uniqueFeatures[i].properties.Phone + '</a></p><p class="bl-map-link"><a href="https://test.com/">' + uniqueFeatures[i].properties.Source + '</a></p></div>'; } } // 最后记得把拼接好的HTML插入到页面DOM中,比如: // document.getElementById('target-container').innerHTML = listContent; }
内容的提问来源于stack exchange,提问作者mm24mm
相关产品推荐
相关产品推荐

