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('0') === 0 && string2int('12345') === 12345 && string2int('12300') === 12300) { if (string2int.toString().indexOf('parseInt') !== -1) { alert('请勿使用parseInt()!'); } else if (string2int.toString().indexOf('Number') !== -1) { alert('请勿使用Number()!'); } else { alert('测试通过!'); } } else { alert('测试失败!'); }
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!