Array.toString returns 循环外为空

Array.toString returns empty outside of loop

我是 JavaScript 的新手,如果这是一个愚蠢或重复的问题,我深表歉意。

我有一个数组和循环,在我每次记录的循环中,它会 return 类似于: A1、A1 A2、A1 A2 A3...等等,直到完成循环。

最后,我尝试记录最终的数组值,但它 return 是空的。

有什么想法吗?

  var testArray: any = new Array();
  var test: any;

  cy
    .get('element')
    .each(function ($el, index) {
      test= $el.text();
      testArray.push(test);
      cy.log(testArray.toString())
    })
  cy.log(testArray.toString())

谢谢

您可以使用.then();引用自 cypress documentation for .then():

.then() is modeled identically to the way Promises work in JavaScript. Whatever is returned from the callback function becomes the new subject and will flow into the next command (with the exception of undefined).

尝试这样的事情:

var testArray: any[] = new Array();

cy
    .get('element')
    .each(($el) => {
        testArray.push($el.text());
        cy.log(testArray.toString());
    ).then(() => cy.log(testArray.toString())
});