交流群号:611979698 【目前还没啥人,欢迎加入一起探讨学习~~】
javascript reduce()函数的用法():
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
reduce函数可接受一个function函数以及一个initialValue(传入的初始值)的初始值。
其中function函数接受四个参数分别为total(每次计算的返回值),currentValue(当前数组的元素值),currentIndex(当前数组元素的索引值),arr(当前数组元素)
reduce()函数的应用
1.实现数组的累加操作。
<!DOCTYPE html>
<html>
<head>
<title>reduce函数</title>
</head>
<script type="text/javascript">
function getSum(){
document.getElementsByClassName('result')[0].innerText = ' ';
let _val = document.getElementById("input").value;
console.log(_val);
if(_val.trim() == '')
{
alert('请输入数字!');
return
}
// if(_val.includes)
let _valarr = _val.split(',');
let _result = _valarr.reduce( (result,value) => {return parseInt(result) + parseInt(value)});
document.getElementsByClassName('result')[0].append(_result);
}
</script>
<body>
<input type="" name="" id="input" class="input" placeholder="输入数字以,分割" />
<button onclick="getSum();">求和</button>
<div class="result"></div>
</body>
</html>
注:通过for循环以及while循环也可以做到数组各项的累加操作,但reduce方法所需耗时最短,有助于提升速度。
2.实现数组的合并
a = b.reduce( function(coll,item){
coll.push( item );
return coll;
}, a );
注:不推荐使用,es6提供了更好的方法来合并两个数组:
a = [...a,...b];