<template>
<div>
<div>
<button @click="push">push:添加到数组末尾</button><br>
<button @click="pop">pop:从数组末尾移除最后一项</button><br>
<button @click="shift">shift:移除数组中的第一个项</button><br>
<button @click="unshift">unshift:添加数组到数组前端</button><br>
<button @click="splice">splice(index,num) index从第几个元素开始 num删除几个</button><br>
<button @click="sort">sort:用每个数组项的toString()方法,然后比较得到的字符串排序</button><br>
<button @click="reverse">reverse:颠倒数组中元素的顺序</button>
</div>
<ul>
<li v-for="(item, index) in items" :key="index">
{{ item.message }}
</li>
</ul>
</div>
</template>
<script>
export default {
name: "HelloWorld",
data() {
return {
items: [
{
message: "Foo",
},
{
message: "Bar",
},
{
message: "Baz",
},
],
addValue: {
message: "这是新加进来的",
},
addValue2: {
message: "这是新加进来的2",
},
};
},
methods: {
push() {
//任意数量的参数 把它们逐个添加到数组末尾,并返回修改后数组的长度
var pushs = this.items.push(this.addValue, this.addValue2);
console.log(pushs); //返回的是修改过后的数组长度
},
pop() {
//从数组末尾移除最后一项,减少数组的length值,然后返回移除的项
console.log(this.items.pop().message); //返回的值是移除掉的项
console.log(this.items.length);
},
shift() {
//移除数组中的第一个项并返回该项,同时数组的长度减1
console.log(this.items.shift().message); //返回的值是移除掉的项
console.log(this.items.length);
},
unshift() {
//在数组前端添加任意个项并返回新数组长度
var unshifts = this.items.unshift(this.addValue, this.addValue2);
console.log(unshifts); //返回的是修改过后的长度
},
splice() {
//删除原数组的一部分成员,并可以在被删除的位置添加入新的数组成员
var splices = this.items.splice(1,2 ); //splice(index,num) index从第几个元素开始 num删除几个
console.log(splices[0].message,splices[1].message); //返回的是删除的值
},
sort() {
//用每个数组项的toString()方法,然后比较得到的字符串排序,返回经过排序之后的数组
var sorts = this.items.sort();
console.log(sorts); //返回的是重新排序之后的数组
},
reverse() {
//颠倒数组中元素的顺序
var reverses = this.items.reverse();
console.log(reverses); //返回的是颠倒后的数组
},
},
};
</script>
<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
</style>