How to count the number of odd elements in a JS array?
This is a question raised by the group of friends, most of the group of friends give the traversal and then the 2 modulo, the final result.
This kind of writing is the most easy to get, then there are no other ideas?
Here I provide another way of thinking, we know that the odd number is actually 1 3 5 7 9 as the end of the numbers, then as long as the statistics of the number of occurrences is enough, but the light such statistics easy to calculate, so we can first with commas together, with a comma to calculate, Because JS is not PHP so convenient to use the Substr_count function to count the number of occurrences of the string, so we directly use regular replacement, calculate the length difference to get the number, the code is as follows:
This idea is also my whim, the feeling is still some ingenious, after all, although this problem is simple, but assuming this array is very large, then its cycle difficulty is increased, and every time to take modulo operation, wasting a lot of performance, after all, even is not required to participate in the calculation, but do not participate in the calculation and do not know it is even So here is a direct substitution, then the length difference calculation can know exactly how many odd!
Count the number of odd elements in the JS array