【数组方法】(笔记)

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);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值