数组的操作方法
1.join() 把数组的所有元素放入一个字符串。元素通过指定的分隔符进行分隔。
2.push() 向数组的末尾添加一个或更多元素,并返回新的长度。
3.pop() 删除并返回数组的最后一项
4.shift() 删除并返回数组的第一项
5.unshift()在数组前端添加任意个项并返回新数组的长度
6.reverse() 颠倒数组中元素的顺序
7.sort() 对数组的元素进行排序
8.toString()返回数组的字符串
9. splice() 删除元素,并向数组添加新元素。
下面通过一个遍历一个小数组来感受一下
<div id="app">
<ul>
<li v-for="(item,index) in items">{{item}}</li>
<button @click="dele(index)">splice--delete</button>
</ul>
<button @click="pushMsg">push</button>
<button @click="popMsg">pop</button>
<button @click="shiftMsg">shift</button>
<button @click="unshiftMsg">unshift</button>
<button @click="sortMsg">sort</button>
<button @click="reverseMsg">reverse</button>
<button @click="spliceMsg1">splice--add</button>
<button @click="spliceMsg2">splice--edit</button>
<button @click="filterMsg">filter</button>
</div>
<script>
var app=new Vue({
el:'#app',
data:{
items:[1,2,3,4,5,6,7,8,9,10]
},
methods:{
pushMsg(){
this.items.push(Math.ceil(Math.random()*10))
},
popMsg(){
this.items.pop()
},
shiftMsg(){
this.items.shift()
},
unshiftMsg(){
this.items.unshift(Math.ceil(Math.random()*10))
},
sortMsg(){
this.items.sort((a,b)=>{
return b-a
})
},
reverseMsg(){
this.items.reverse()
//如果是字符串需要逆排序的话
// split('').reverse().join('')
},
dele(index){
this.items.splice(index,1)
},
spliceMsg1(){
var n1=Math.floor(Math.random()*this.items.length);
var n2='插入的值:'+Math.ceil(Math.random()*10)
this.items.splice(n1,0,n2)
},
spliceMsg2(){
var n1=Math.floor(Math.random()*this.items.length);
var n2='先删除后插入的值:'+Math.ceil(Math.random()*10)
this.items.splice(n1,1,n2)
},
filterMsg(){
this.items=this.items.filter((item,index)=>{
return item%2==0
})
}
}
})
</script>
以下是五种数组迭代的方法
1.every():对数组中的每一项运行给定函数,如果该函数对每一项都返回 true,则返回 true。
2.filter():对数组中的每一项运行给定函数,返回该函数会返回 true 的项组成的数组。
3。forEach():对数组中的每一项运行给定函数。这个方法没有返回值。
4.map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
5. some():对数组中的每一项运行给定函数,如果该函数对任一项返回 true,则返回 true。
除此之外 ECMAScript 5 还新增了两个归并数组的方法:reduce()和 reduceRight()。
这两个方法都会迭代数组的所有项,然后构建一个最终返回的值。其中,reduce()方法从数组的第一项开始,逐个遍历到最后。而 reduceRight()则从数组的最后一项开始,向前遍历到第一项。