Home >Web Front-end >JS Tutorial >The implementation of enumeration finds all the numbers with 1 in 1-1000 and calculates the number of 1 occurrences_javascript skills

The implementation of enumeration finds all the numbers with 1 in 1-1000 and calculates the number of 1 occurrences_javascript skills

WBOY
WBOYOriginal
2016-05-16 17:22:591352browse

I was fortunate enough to get a small interview question recently. I studied it and then shared it. I hope it will be helpful to everyone's coding career.

The interview question is: Find all numbers from 1-1000 that appear 1, and count the number of 1 occurrences

Solution:

Copy code The code is as follows:

//The enumeration method can only be viewed under Google Chrome
(function () {
var tmp = [];
for (var i = 1; i< 1001; i){
/1/g.test('' i-1) && tmp.push(i);
}
console.log(tmp.length)

console.log(tmp.reduce(function(i,j) {
return i j
}))

}) ()

The above is the implementation method of enumeration, but it does not work if you go from 1-N, because N may not be how many.
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn