如何获取JSON中名称相似且非空的所有配料元素?
解决方法
你的问题出在几个关键细节上,直接给你修正后的方案:
问题点分析
- 动态访问对象属性时,不能用
dataCocktail.strIngredient+number这种写法,得用方括号语法来拼接属性名 Array.push()返回的是数组的新长度,不能把它赋值给ingredients,否则数组会变成数字类型- 没初始化
number和ingredients变量,循环根本无法正常启动 - 循环条件没判断属性是否为有效内容(空字符串、null这类无效值要直接终止循环)
修正后的代码
// 初始化必要变量 const dataCocktail = response.data.drinks[0]; const ingredients = []; let number = 1; // 循环遍历所有配料属性 while (true) { // 用方括号+模板字符串动态访问属性 const currentIngredient = dataCocktail[`strIngredient${number}`]; // 遇到空值或不存在的属性就终止循环 if (!currentIngredient) break; // 将有效配料加入数组 ingredients.push(currentIngredient); number++; } console.log(ingredients); // 现在能拿到所有非空配料了
把配料展示到页面
拿到配料数组后,你可以这样渲染到页面中:
// 假设页面上有个id为ingredients-container的容器 const container = document.getElementById('ingredients-container'); // 逐个创建列表项添加到容器 ingredients.forEach(ing => { const item = document.createElement('p'); item.textContent = ing; container.appendChild(item); }); // 或者用模板字符串一次性渲染(更简洁) container.innerHTML = ingredients.map(ing => `<p>${ing}</p>`).join('');
内容的提问来源于stack exchange,提问作者Renata Blanco
相关产品推荐
相关产品推荐

