简体   繁体   English

计算包含逗号分隔的字符串的数组的长度

[英]Counting length of array containing comma separated strings

Below is my array: 下面是我的数组:

var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"];

Now I want to count length of this record but I would like to treat comma separated records as not a single record 现在,我想计算该记录的长度,但是我想将逗号分隔的记录视为不是单个记录

For eg: abc.mp3, Lmn.mp3 want to to treat as 2 separated records by splitting with comma. 例如:abc.mp3,Lmn.mp3希望通过用逗号分割作为2条分离的记录。

Expected length of array should be: 5 预期的数组长度应为:5

Is there any method which will simplify the process of counting this length instead of doing loop and then splitting each record by comma and then counting length one by one? 有没有一种方法可以简化计算此长度的过程,而不是执行循环,然后通过逗号分割每个记录,然后一一计数长度,从而简化该过程?

You can loop over array and create a new array that will have split values. 您可以遍历数组并创建一个具有拆分值的新数组。 Now you just have to do newArray.length 现在您只需要执行newArray.length

 var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"]; var ret = array.reduce(function(p,c){ return p.concat(c.split(',')); }, []) console.log(ret.length) 

Or, you can create a string and count number of commas and just add 1 to it 或者,您可以创建一个字符串并计算逗号数,然后向其添加1

 var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"]; console.log(array.join().match(/,/g).length + 1) 

join array as string and then split string to array,then you can calculate the array length . 将array作为字符串加入,然后将字符串拆分为array,然后可以计算出array的length

 var array = ["abc.mp3,Lmn.mp3","pqr.mp3","ppp.mp3,ggg.mp3"].join(',').split(','); console.log(array); console.log(array.length); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM