- push() : 该方法用于向数组的末尾添加一个或多个元素,并返回修改后的数组的新长度。
const fruits = ['apple', 'banana'];
fruits.push('orange', 'grape');
console.log(fruits);
// 输出:['apple', 'banana', 'orange', 'grape']
- pop() : 该方法用于从数组的末尾移除最后一个元素,并返回被移除的元素。
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.pop();
console.log(removedFruit);
// 输出:'orange'
console.log(fruits);
// 输出:['apple', 'banana']
- shift() : 该方法用于从数组的开头移除第一个元素,并返回被移除的元素。
const fruits = ['apple', 'banana', 'orange'];
const removedFruit = fruits.shift();
console.log(removedFruit);
// 输出:'apple'
console.log(fruits);
// 输出:['banana', 'orange']
- unshift() : 该方法用于向数组的开头添加一个或多个元素,并返回修改后的数组的新长度。
const fruits = ['banana', 'orange'];
fruits.unshift('apple', 'grape');
console.log(fruits);
// 输出:['apple', 'grape', 'banana', 'orange']
- splice() : 该方法用于从数组中添加或删除元素,并返回被删除的元素组成的数组。
const fruits = ['apple', 'banana', 'orange', 'grape'];
const removedFruits = fruits.splice(1, 2, 'kiwi', 'melon');
console.log(removedFruits);
// 输出:['banana', 'orange']
console.log(fruits);
// 输出:['apple', 'kiwi', 'melon', 'grape']
- sort() : 该方法用于对数组进行原地排序,默认按照字符串的Unicode编码进行排序
const numbers = [3, 1, 5, 2, 4];
numbers.sort();
console.log(numbers);
// 输出:[1, 2, 3, 4, 5]
- reverse() : 该方法用于原地反转数组中的元素顺序。
const fruits = ['apple', 'banana', 'orange'];
fruits.reverse();
console.log(fruits);
// 输出:['orange', 'banana', 'apple']
下面是Vue中的里一个调用,因为Vue对这些基础API进行了封装,封装的对象都是会对原数组进行改动的。
<!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>
<script src="../../vue.js/vue.js"></script>
</head>
<body>
<div id="app">
<div v-for="item in list">{{item.name}}-{{item.age}}</div>
<button @click="change">改变</button>
</div>
<script>
Vue.config.productionTip=false
new Vue({
el: '#app',
data: {
list:[{
name:"张三",age:27
}]
},
methods: {
change(){
this.list.splice(0,1,{name:"李四",age:18})
}
},
});
</script>
</body>
</html>