数组常用方法总结
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
</style>
</head>
<body>
<div id="app">
<h2>reduce计算数字总和-{{allPrice_reduce}}</h2>
<h2>map计算所有的名字为数组-{{allName}}</h2>
<h2>filter过滤出价格小于100的数组-{{allFilterPriceUnder100}}</h2>
<h2>some判断数组的每一项id是否有大于100布尔值-{{IdIsOver100}}</h2>
<h2>every判断数组的每一项id是否全部大于100布尔值-{{allIdIsOver100}}</h2>
</div>
</body>
<script src="./vue.js"></script>
<script>
Vue.config.productionTip = false
let vue = new Vue({
el: '#app',
data() {
return {
books: [
{ id: 99, name: "西游记", price: 119 },
{ id: 106, name: "红楼梦", price: 19 },
{ id: 108, name: "水浒传", price: 109 },
{ id: 109, name: "三国", price: 179 },
]
}
},
computed:{
allPrice_reduce(){
// es6 reduce 返回值为累加后的值 四个属性 1累加器(默认为数组第一个), 2当前值(默认为第二个),3当前值的index,4原数组
return this.books.reduce((acc,cur,curIndex,arr)=>{
// return acc.price + cur.price 第二次的acc为计算后的数字 没有price属性
return (typeof(acc) === 'number' ? acc : acc.price) + cur.price
})
},
// es6 map 返回值为新数组 item(当前值),index(当前值索引),arr(原数组)
allName(){
return this.books.map(item=>item.name)
},
// es6 filter 过滤数组 返回一个新数组 item(当前值),index(当前值索引),arr(原数组)
allFilterPriceUnder100(){
// 符合条件的会被放进新数组返回
return this.books.filter(item=>item.price<100)
},
// es6 some 返回一个布尔值 有一个满足即为true item(当前值),index(当前值索引),arr(原数组)
IdIsOver100(){
return this.books.some(item=>item.id>100)
},
// se6 every 返回一个布尔值 所有满足条件为true item(当前值),index(当前值索引),arr(原数组)
allIdIsOver100(){
return this.books.every(item=>item.id>100)
},
// es6 forEach 遍历数组
allForEach(){
return this.books.forEach((item,index)=>{
console.log(`${index}--${item.name}`)
})
}
}
})
</script>
</html>