1.删除或者替换数组元素,改变原数组
Array.prototype.splice()
示例
2.在数组的后面新增一个或者多个元素,并返回该数组的新长度
Array.prototype.push() 会改变原数组
<script>
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
console.log(count);
console.log(animals);
</script>
3.从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。
Array.prototype.pop()
<script>
const plants = ["broccoli", "cauliflower", "cabbage", "kale", "tomato"];
console.log(plants);//输出原数组
console.log(plants.pop());
console.log(plants);//输出操作以后的数组
</script>
4.从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
Array.prototype.shift()
<script>
const array1 = [1, 2, 3];
console.log(array1); //操作前
const firstElement = array1.shift();
console.log(array1); //操作后
console.log(firstElement); //被删除的元素
</script>
5.将一个或多个元素添加到数组的开头,并返回该数组的新长度
Array.prototype.unshift() (该方法修改原有数组)。
<script>
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
console.log(array1);
</script>
6.对数组进行排序
Array.prototype.sort()
数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串
arr.sort((a, b) => {
return this.sortType === 1 ? a.age - b.age : b.age - a.age;
});
7. 将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。
Array.prototype.reverse() 该方法会改变原数组。
8.创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。犹如筛选
Array.prototype.filter()
不会改变原数组,它返回过滤后的新数组,需要一个元素进行接收
9.对一个数组内,满足一定条件的数组项,的数目,进行统计,返回的是一个数字
Array.prototype.reduce()
例如下:masterNumber是一个计算属性
找出满足年龄小于20岁学生的个数
persons有几项,reduce就会执行几次
当达到第四次,pre的值就是第三次的返回值,假设为3,那么第四次的返回值就是4
而第四次的返回值也是整个函数的返回值
masterNumber() {
// reduce(a,b),a是一个函数,b是一个初始值
//pre第一次的值是初始值b,也就是0;pre第二次的值是上一次执行返回值,以此类推
//cur是persons数组内的每一项,
let x = this.persons.reduce((pre, cur) => {
return pre + (cur.age < 20? 1 : 0);
}, 0);
return x;
},
简写如下
masterNumber() {
return this.persons.reduce((pre, cur) =>pre + (cur.age < 20? 1 : 0)
, 0);
}