gpt4 book ai didi

javascript - 如何在javascript中使用for循环显示两个对象的数据

转载 作者:行者123 更新时间:2023-12-02 21:12:18 25 4
gpt4 key购买 nike

我创建了两个对象来显示帐号和可用余额帐号正在显示帐号,但是当我尝试使用内部 for 循环显示可用余额时,仅显示最后一个值,请任何人帮助我。

enter image description here

数据将显示为屏幕截图

enter image description here

var acctInfo = [
{
"acctNum": "AAA - 1234",
"user": "Alice"
},
{
"acctNum": "AAA - 5231",
"user": "Bob"
}];

var balances = {
"AAA-1234": 4593.22,
"AAA-9921": 0
}

function bankinfo(){
for(var i=0; i<acctInfo.length; i++){

var div = document.createElement('div');
div.setAttribute('class', 'border-bottom p-3 mx-2');
var h5 = document.createElement('h5');
h5.setAttribute('class', 'd-inline text-primary');
var h6 = document.createElement('h6');
h6.setAttribute('class', 'float-right d-inline');
div.appendChild(h5);
div.appendChild(h6);

h5.innerHTML = acctInfo[i].acctNum;
var result = Object.values(balances);
// Printing values
for(var j = 0; j < result.length; j++) {
h6.innerHTML = "$"+result[j];
}
document.querySelector('.main-card').appendChild(div);
}

}
bankinfo();
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<main class="col-5 m-2 p-0 main-card" id="data-content">
<div class="bg-light border-bottom p-3">
<h5 class="d-inline">Account</h5>
<h5 class="float-right d-inline">Available Cash </h5>
</div>
</main>

最佳答案

const acctInfo = [
{
acctNum: "AAA-1234",
user: "Alice",
},
{
acctNum: "AAA-5231",
user: "Bob",
},
];

const balances = {
"AAA-1234": 4593.22,
"AAA-5231": 0,
};

function bankinfo() {
acctInfo.forEach((item) => {
const div = document.createElement("div");
const h5 = document.createElement("h5");
const h6 = document.createElement("h6");

div.setAttribute("class", "border-bottom p-3 mx-2");
h5.setAttribute("class", "d-inline text-primary");
h6.setAttribute("class", "float-right d-inline");

h5.textContent = item.acctNum;
h6.textContent = balances[item.acctNum];

div.appendChild(h5);
div.appendChild(h6);

document.querySelector(".main-card").appendChild(div);
});
}
bankinfo();
    <link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

<main class="col-5 m-2 p-0 main-card" id="data-content">
<div class="bg-light border-bottom p-3">
<h5 class="d-inline">Account</h5>
<h5 class="float-right d-inline">Available Cash </h5>
</div>
</main>

如果两个对象都有正确的记录,则不需要第二次循环

如果你还想...你可以这样做

const result = Object.keys(balances);
result.forEach(x => {
if(item.acctNum.toLowerCase() === x.toLowerCase()) {
h6.innerHTML = "$"+balances[x];
}
});

关于javascript - 如何在javascript中使用for循环显示两个对象的数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61058288/

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