Home  >  Article  >  Web Front-end  >  Detailed explanation of usage examples of the reduce() method that comes with JavaScript

Detailed explanation of usage examples of the reduce() method that comes with JavaScript

高洛峰
高洛峰Original
2016-12-28 09:42:271535browse

1. Method description, Array's reduce() applies a function to [x1, x2, x3...] of this Array. This function must receive two parameters, and reduce() continues the result with the sequence. The next element is cumulatively calculated, and the effect is:

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)

2. Usage example

'use strict';
function string2int(s){
if(!s){
alert('the params empty');
return;
}
if(s.length===1){
return s*1;
}
var arr = [];
for(var i=0; i<s.length; i++){
arr.push(s.substr(i, 1)*1);
}
return arr.reduce(function(x, y){
return x*10 + y;
});
}
// 测试:
if (string2int(&#39;0&#39;) === 0 && string2int(&#39;12345&#39;) === 12345 && string2int(&#39;12300&#39;) === 12300) {
if (string2int.toString().indexOf(&#39;parseInt&#39;) !== -1) {
alert(&#39;请勿使用parseInt()!&#39;);
} else if (string2int.toString().indexOf(&#39;Number&#39;) !== -1) {
alert(&#39;请勿使用Number()!&#39;);
} else {
alert(&#39;测试通过!&#39;);
}
}
else {
alert(&#39;测试失败!&#39;);
}

The above is an example of the use of the reduce() method in JavaScript introduced by the editor. Detailed explanation, I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to you in time. I would also like to thank you all for your support of the PHP Chinese website!

For more detailed usage examples of the reduce() method that comes with JavaScript, please pay attention to the PHP Chinese website for related articles!

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