gpt4 book ai didi

javascript - 遍历对象并显示存在 Y 的数据

转载 作者:行者123 更新时间:2023-11-30 06:25:09 25 4
gpt4 key购买 nike

我有一个对象,它有一个名为 response 的属性,它包含一个带有 Y 和 N 的字符串。下一个属性是详细信息,其顺序与响应相同,例如第一个 Y 与 details.1 相关,第二个 N 与 details.2 相关,等等。如何循环遍历此对象并显示一个段落和一个仅用于具有相应 Y 的细节的图像。

var options = {
response: "YNY",
details: {
1: {
text: "This is the first option",
img: "http://www.placecage.com/200/300"
},
2: {
text: "This is the second option",
img: "http://www.placecage.com/200/300"
},
3: {
text: "This is the third option",
img: "http://www.placecage.com/200/300"
}
}
};

var resp = options.response.split("");
var options = options.details;

最佳答案

你快到了。 split('') 没问题。您可以进一步遍历此数组并为要添加到页面的 HTML 创建一个字符串值作为 options.details[index+1] 然后创建 p和进入页面的 img 标签。

var options = {
response: "YNY",
details: {
1: {
text: "This is the first option",
img: "http://www.placecage.com/200/300"
},
2: {
text: "This is the second option",
img: "http://www.placecage.com/200/300"
},
3: {
text: "This is the third option",
img: "http://www.placecage.com/200/300"
}
}
};

var resp = options.response.split("");
var nHTML = '';
resp.forEach(function(character, index){
if(character === 'Y'){
nHTML+= '<p> '+options.details[index+1].text+'<img src="'+options.details[index+1].img+'"></p>';
}
});
document.getElementById('container').innerHTML = nHTML;
<div id='container'></div>

关于javascript - 遍历对象并显示存在 Y 的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50969992/

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