Is there a way to find the length of this array, and all the sub arrays inside it. Meaning 13 and not 6? Without having to use loops and adding up all the elements inside the arrays.
有没有办法找到这个数组的长度,以及里面所有的子数组。意思是13而不是6?不需要使用循环并将数组中的所有元素相加。
I'm looking for one command that can do this.
我在寻找一个能做到这一点的命令。
[1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]
3 个解决方案
#1
1
A bit of a hack, but you can do
有点小技巧,但你能做到
arr.toString().split(',').length
join(',')
would work as well, it flattens everything
join(',')也可以工作,它使一切变得扁平
var arr = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];
console.log(arr.toString().split(',').length)
if all you wanted was the number of indices in total
如果你想要的是指数的总数。
If the array contains commas inside the indices, those could be removed for the same effect
如果数组在索引中包含逗号,那么可以删除它们,以获得相同的效果
JSON.stringify(arr).replace(/"(.*?)"/g,'1').split(',').length
#2
2
try flatting it
试着使变平它
[].concat.apply([], [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]).length
#3
1
-
Array#reduce
could be used but [at your own risk]数组#reduce可以使用,但是[您自己承担风险]
-
Use
Array.isArray
to determine whether the passed value is anArray
.使用数组。isArray用来确定传递的值是否为数组。
var input = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];
var length = input.reduce(function(a, b) {
return a + (Array.isArray(b) ? b.length : 1);
}, 0);
console.log(length);
#1
1
A bit of a hack, but you can do
有点小技巧,但你能做到
arr.toString().split(',').length
join(',')
would work as well, it flattens everything
join(',')也可以工作,它使一切变得扁平
var arr = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];
console.log(arr.toString().split(',').length)
if all you wanted was the number of indices in total
如果你想要的是指数的总数。
If the array contains commas inside the indices, those could be removed for the same effect
如果数组在索引中包含逗号,那么可以删除它们,以获得相同的效果
JSON.stringify(arr).replace(/"(.*?)"/g,'1').split(',').length
#2
2
try flatting it
试着使变平它
[].concat.apply([], [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]]).length
#3
1
-
Array#reduce
could be used but [at your own risk]数组#reduce可以使用,但是[您自己承担风险]
-
Use
Array.isArray
to determine whether the passed value is anArray
.使用数组。isArray用来确定传递的值是否为数组。
var input = [1, [4, 5, 2, 1], 2, [4, 5, 2, 6], 2, [3, 3]];
var length = input.reduce(function(a, b) {
return a + (Array.isArray(b) ? b.length : 1);
}, 0);
console.log(length);