gpt4 book ai didi

javascript - for循环检查三个数组的索引是否匹配,如果匹配则创建不同的对象

转载 作者:行者123 更新时间:2023-11-28 14:26:25 28 4
gpt4 key购买 nike

我需要检查三个不同的数组以查看它们的索引是否匹配。如果它们匹配,则创建一个对象。第三个数组中的项目可能较少。如果第三个数组的项目较少,则前两个数组应继续检查其索引是否匹配并创建不同的对象。与“seqIds”数组中的索引匹配的数组索引应添加“seqId”作为属性,其他两个数组中与“seqId”索引不匹配的索引不会获得“seqId”属性。

Edit: The invIds and invTypes arrays will always be the same length.

数组示例:

invIds:   [1, 2, 3, 4];
invTypes: ["A", "B", "C", "D"];
seqIds: [10, 11];

invs 数组应包含以下对象:

invs: [
{
"invId": 1,
"invType": "A",
"seqId": 10
},
{
"invId": 2,
"invType": "B",
"seqId": 11
},
{
"invId": 3,
"invType": "C"
},
{
"invId": 4,
"invType": "D"
}
];

我写的for循环:

var invs = [];

for (var invI = 0; invI < this.state.invIds.length; invI++) {
for (var invT = 0; invT < this.state.invTypes.length; invT++) {
for (var invS = 0; invS < this.state.invSeqIds.length; invS++) {
if (invI === invT && invT === invS) {
invs.push({
seqId: this.state.invSeqIds[invS],
userId: this.state.invIds[invI],
invTypeCd: this.state.invTypes[invT],
importId: randInt
});
}
}
if (invI === invT) {
invs.push({
userId: this.state.invIds[invI],
invTypeCd: this.state.invTypes[invT],
importId: randInt
});
}
}
}

我编写的 for 循环没有正确添加到数组中,它执行以下操作:

{"invId": 1, "invType": "A", "seqId": 10}
{"invId": 1, "invType": "A"}
{"invId": 2, "invType": "B", "seqId": 11}
{"invId": 2, "invType": "B"}
{"invId": 3, "invType": "C"}
{"invId": 4, "invType": "D"}

最佳答案

解决此问题的另一种方法是使用 while-statement与运算符(operator)一起in检查源数组的索引。

let invIds = [1, 2, 3, 4],
invTypes = ["A", "B", "C", "D"],
seqIds = [10, 11],
result = [],
i = 0;

while (i in invIds && i in invTypes) {
result[i] = Object.create(null);
result[i].invId = invIds[i];
result[i].invType = invTypes[i];
if (i in seqIds) result[i].seqId = seqIds[i];
i++;
}

console.log(result);
.as-console-wrapper {max-height: 100% !important;top: 0;}

关于javascript - for循环检查三个数组的索引是否匹配,如果匹配则创建不同的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53109292/

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