将元素推送到回调函数内部的数组中

时间:2017-10-02 11:12:32

标签: javascript asynchronous nightwatch.js

所以我为此使用夜视仪并且似乎无法将元素推送到回调内的数组。它显示" undefined"。

            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]);

                });

            };

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

你刚刚写了一个错字:)你正试图推进标签。但是你定义的数组叫做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