js中数组的遍历方法
<body>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<div class="item"></div>
<script>
var data = [
{name: 'zz',age: 18},
{name: 'xx',age: 20},
{name: 'yy',age: 19},
];
var oDiv = document.getElementsByClassName('item');
es5中
forEach
filter
every
some
reduce/reduceRight
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
data.forEach(function(item,index){
oDiv[index].innerText = index+1+".我叫"+item.name+",年龄"+item.age
})
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//filter,过滤,返回所有符合条件数据组成的新数组
var result = data.filter(function(item,index,self){
return item.age > 19;
})
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//every,判断所有项是否符合条件,返回值为布尔值,都为true则返回true
console.log(data.every(function(item,index){
return item.age > 18;
}))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//some,判断是否存在符合条件的项,存在就返回true,
console.log(data.some(function(item,index){
return item.age > 18;
}))
![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
//reduce,累加器,reduceRight倒着查询
// reduce(function(prevData,current,index,self){},initValue)
var str = data.reduce(function(prevData,current){
return prevData + current.name + ','
},'名字都是')
</script>