我想實作一個函式并在其中使用一個 forEach 來遍歷兩個物件。我必須每次迭代比較兩個值。
示例/想法:
const id = {a:'A2', b: 'B1', c:'C3'};
const name = {maria:'Maria',josef:'Josef',moses:'Moses'};
Object.values(id, name).forEach((ID, NAME) => {
cy.contains(ID);
cy.contains(NAME);
});
如果我像這樣使用兩個 forEach 回圈:
Object.values(id).forEach((ID) => {
Object.values(name).forEach((NAME) => {
cy.contains(ID);
cy.contains(NAME);
});
});
從邏輯上講,它不會均勻地迭代。
謝謝你的幫助!
uj5u.com熱心網友回復:
cy.contains(ID)并cy.contains(NAME)搜索獨立元素 - 您可以獨立回圈。
Object.values(id).forEach((ID) => {
cy.contains(ID);
})
Object.values(name).forEach((NAME) => {
cy.contains(NAME);
})
除非您想在同一個元素上同時檢查 id 和 name,否則這種情況cy.contains(...)太簡單了。
您可以通過索引關聯值
Object.values(id).forEach((ID, index) => {
const NAME = Object.values(name)[index]
cy.contains(`#${ID}`, NAME); // get element with id of ID and text of NAME
// e.g <div id="A2">Maria</div>
})
順便說一句,串列最好使用復數形式,串列項使用單數形式,而不是小寫和大寫。
我保留了您的約定以使更改更清晰,但請考慮namesand name, idsand id。
uj5u.com熱心網友回復:
當心,依靠財產秩序是自找麻煩。屬性順序復雜。這取決于物件的創建方式和屬性的名稱。例如,這兩個物件中的屬性順序不同。一些例子:
顯示代碼片段
// The properties in these objects are in a *different* order from one another
const ex1a = {x: 1, y: 2};
const ex1b = {y: 2, x: 1};
console.log(sameOrder(ex1a, ex1b)); // false
// Less obviously, the order of the properties in these two objects
// **is the same**:
const ex2a = {"2": 1, x: 2};
const ex2b = {x: 2, "2": 1};
console.log(sameOrder(ex2a, ex2b)); // true
// The order of these is the same:
const ex3a = {};
const ex3b = {a: 1, b: 2};
ex3a.a = 1;
ex3a.b = 2;
console.log(sameOrder(ex3a, ex3b)); // true
// But the order of these is different:
const ex4a = {};
const ex4b = {a: 1, b: 2};
ex4a.b = 2;
ex4a.a = 1;
console.log(sameOrder(ex4a, ex4b)); // false
// And so on.
function sameOrder(a, b) {
const anames = Object.keys(a);
const bnames = Object.keys(b);
return anames.length === bnames.length &&
anames.every((aname, index) => aname === bnames[index]);
}
但是,如果您不關心順序而只關心值,只需將值作為陣列獲取,然后使用簡單的回圈:
const idValues = Object.values(id);
const nameValues = Object.values(name);
for (let i = 0, max = Math.max(idValues.length, nameValues.length); i < max; i) {
const idValue = idValues[i];
const nameValue = nameValues[i];
// ...do something with `idValue` and `nameValue`...
// Note that if the arrays aren't the same length, one of those will be `undefined`
// once the loop has gone beyond the length of the array it came from.
}
uj5u.com熱心網友回復:
謝謝你們!
用你的例子我解決了我的問題。
解決方案:
const names = Object.values(name);
Object.values(id).forEach((ID, index) => {
cy.contains(ID);
cy.contains(names[index]);
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/447656.html
下一篇:將值插入物件并回傳值
