如何计算多维数组中的项目总数?

时间:2017-06-23 01:31:34

标签: javascript node.js selenium-webdriver protractor selenium-chromedriver

以下是我用来从我的转发器表中检索数据的代码。 这给出了多维数组中的输出。请检查输出。

我想得到整个多维数组中的项目总数和每个数组中的项目总数。

更详细地说,整个多维数组有30个项目,每个数组中有6个项目我想得到这两个值。 如何计算这两个值?

var RepeaterTable = element.all(by.repeater("view in ctrl.view track by $index")).each(function(rowelem,index){
                     rowelem.getText().then(function(BlockTrans){
                         console.log("****index and RowElem\n"+index+"\n",BlockTrans);
                         var item = BlockTrans;
                     });


                 });  

输出上面的代码

0
Morrison
Male
Jun 22, 2017
26
Yes
Edit
****index and RowElem
1
Steven
Male
Jun 22, 2017
39
Yes
Edit
****index and RowElem
2
Emy
Female
Jun 22, 2017
27
Yes
Edit
****index and RowElem
3
Emily
Female
Jun 22, 2017
18
Yes
Edit
****index and RowElem
4
Michael
Male
Jun 22, 2017
46
Yes
Edit

1 个答案:

答案 0 :(得分:1)

递归遍历每个元素,计算所有元素,如果它是一个数组并返回金额

示例

function getTotalElementCount (obj) {
    /* This number will contain the total amount of elements in the given variable obj.
     * This means all subelements will also be counted there.
     */
    let count = 0; 
    // If obj is an array, we want to find out how many elements and subelements it contains
    if (obj instanceof Array) {
        // We call this function for every element (elem) in obj to get the total amount of elements in elem
        obj.foreach ((elem) => {
            // We increment the count by all elements in elem
            count += getTotalElementCount(elem);
        }
    } else {
         /* Element is not an array, so we can't go deeper. 
          * This means this obj is only a single element
          */
        return 1;
        /* you can also do this.
         * count = 1;
         */
    }
    return count;
}

如果我的例子不够清楚,请告诉我