下面是我用来从中继器表中检索数据的代码。 这给出了多维数组的输出。请也检查输出。
我想获取整个多维数组中的项目总数以及每个数组中的项目总数。
更详细地说,整个多维数组有 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
最佳答案
递归遍历每个元素,如果是数组则统计所有元素并返回数量
示例
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;
}
如果我的例子不够清楚,请告诉我
关于javascript - 如何计算多维数组中的项目总数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44711723/