【问题标题】:Pushing Elements into an Array That Is Inside a Callback Function将元素推送到回调函数内部的数组中
【发布时间】:2023-03-26 19:17:02
【问题描述】:

所以我为此使用了 nightwatch 并且似乎无法将元素推送到回调内的数组。它显示“未定义”。

            var tab = [];

            exports.command = function (control,tabs)
            {
                var self=this;
                var split = tabs.split("~"); //DELIMIT "tabs" PARAMETER

                self.elements('css selector', control+" :first-child", function (result) //COUNT THE CHILD OF PARENT
                {
                    var x = result.value;
                    var screenTabLen = x.length; //GET THE LENGTH OF ACTUAL TABS IN THE SCREEN
                    var tabLen = split.length; //GET THE LENGTH OF DELIMITED "tabs"     

                    function getTabText(index)
                    {
                        self.getText(control + " > :nth-child(" + index + ")", function(result){
                            tab.push(result.value);             
                        });

                    }

                    for (i=1; i<screenTabLen; i++)
                    {
                        getTabText(i);
                    }

                    console.log("TAB >> " + tab[1]);

                });

            };

我该如何解决这个问题?提前致谢! 编辑:粘贴整个代码

【问题讨论】:

  • 什么是标签?你只初始化一个bat数组
  • 这是一个错字。当你应该推送到 bat 时,你正在推送到 tab
  • 您可以通过使用 linter 来防止将来出现此类错误,例如 ESLint
  • 你还是有错别字.. 在 console.log() 中它仍然是 bat

标签: javascript asynchronous nightwatch.js


【解决方案1】:

您刚刚打错了 :) 您正在尝试推送到选项卡。但是你定义的数组叫做bat。

var bat = []; //global variable
//here is your array called bat. 
            function getTabText(index)
            {
                self.getText(control + " > :nth-child(" + index + ")", function(result){
                    bat.push(result.value); //push values to array 
                    //change the tab to bat and you are good.


                });

            }

            for (i=1; i<screenTabLen; i++)
            {
                getTabText(i); //loop function 
            }

            console.log("TAB === " + bat[1]); //getting undefined here

【讨论】:

  • 你的 console.log("TAB === " + bat[1]);现在应该是标签。
【解决方案2】:

tab.push() 更改为bat.push() 或将所有bat 更改为tab

var bat = []; // global variable

function getTabText(index) {
    self.getText(control + " > :nth-child(" + index + ")", function(result) {
        bat.push(result.value); // push values to array          
    });    
}

for (i=1; i<screenTabLen; i++) {
    getTabText(i); // loop function 
}

console.log("TAB === " + bat[1]); // getting undefined here

【讨论】:

  • 向他解释你在答案中的不同之处,而不仅仅是显示代码
  • @AthMav 我更新了 console.log。可悲的是仍然没有工作
  • 您确定 tab[1] 存在吗?尝试打印整个数组。如果您可以提供更多代码,请使用 console.log(tab)。
  • @YoDawgyDawg 我看不出有什么问题,但您已将其标记为异步,所以一定是它......
猜你喜欢
  • 2021-08-29
  • 1970-01-01
  • 2019-09-01
  • 1970-01-01
  • 2018-07-07
  • 2018-09-19
  • 1970-01-01
  • 2013-01-21
相关资源
最近更新 更多