使用Javascript:数组不保留值

问题描述 投票:0回答:2

在下面的代码段中,

function retreive_data_from_UI() {
    let arr_rows = [];
    cy.get(constants.cssCustomerWoListViewTable).children().each(($rows, ind) => {
        arr_rows.push($rows.text());
        cy.log(ind);
        cy.log(arr_rows[ind]);
    });
    cy.wait(1000);
    for(var i = 0; i < 5; i++){
        // I tried both separately pop() and accessing by index
        cy.log(arr_rows.pop());
        // or
        cy.log(arr_rows[i]); 
    }
    return arr_rows;
}

对于arr_rows [IND]的值被印刷cy.get()内。孩子()。每个(()=> {})块,但不是在for循环它后面。下面是输出

Output

任何人都可以指出我哪里错了?我使用的柏树编写前端测试。

javascript cypress
2个回答
1
投票

这可能是因为你正在申报let arr_rows,意思是块范围。您正试图填补它在一个匿名函数,它有自己的范围,因此其自身arr_rows

声明arr_rowsvar arr_rows = [],它应该工作。

here了解更多详情。


1
投票

我解决了这个通过使用(Return from a promise then())的建议:

创建并返回一个承诺。这样我可以在其他功能使用解析值(this.result)了。

function retreive_data_from_UI(){
  var result = [];
  return new Promise(function(resolve){
    cy.get(constants.cssCustomerWoListViewTable).children().each(($rows, ind) => {
      result.push($rows.text());
    }).then(function(){
      this.result = result;
      for(var i = 0; i < 5; i++){
        cy.log(this.result[i]) // content printed here
      }
      resolve(this.result)
    });
  });
} 

在其他功能使用的this.result值

it('Test WO Sorting Ascending', () => {
    cy.get(constants.btnLmsWOSortAsc)
    .click()
    .then(function() {
      retreive_data_from_UI()
      .then(function(result){
        for(var i = 0; i < 5; i++){
          cy.log(result[i]); // content printed properly here too
        }
      });
    });
}); 
© www.soinside.com 2019 - 2024. All rights reserved.