数组方法看这里够了

123 阅读8分钟

1665148176376

every( )方法的定义与使用:

  • every( )方法用于检测数组中每个元素是否都符合指定条件(该条件为一个函数)
  • every( )方法会遍历数组的每一项,如果有一项不满足条件,则表达式返回 false,剩余项不会再执行检测;如遍历完数组后每一项都符合条件,则返回true

语法:

array.every(function(currentValue,index,arr), thisValue)

参数说明:

  • 第一个参数为一个回调函数,必传项,数组中的每一项都会遍历执行 该函数
    1. currentValue : 必传,当前项的值
    2. index : 选传,当前项的索引值
    3. arr : 选传,当前项所属的数组对象
  • 第二个参数thisValue为可选参数,回调函数中的this会指向该参数对象。

**Notice: **

  • every( ) 若是对一个空数组,进行检测,无论什么条件下都会返回true
  • every( )方法不会改变原数组

上代码:

const arr = [10, 9, 22, 55, 60];
      const res = arr.every(function (currentValue, index, arr) {
        console.log(currentValue, index, arr);
        return currentValue > 30;     //数组中的每个元素的值都要大于30的情况,最后才返回true
      });
      console.log(res);

1664525800957

如果这样看,就能看到他的执行流程了,上面的代码判断在第一步判断的时候拿10去和30比较,结果为false就直接return出去结果,就没往下执行了,看下面代码来看,就能看到执行机制了

const arr = [10, 9, 22, 55, 60];
      const res = arr.every(function (currentValue, index, arr) {
        console.log(currentValue, index, arr);
        return currentValue < 30;   //只是吧大于号换成了小于号
      });
      console.log(res);

1664526086851


some( )方法的定义与使用:

  • some( )方法会遍历数组中的每个元素,让每个值执行一遍callback函数,如果有一个元素满足条件,返回true,剩余的元素不会再继续执行检测.如果没有满足条件的元素,则返回false

语法:

array.some(function(currentValue,index,arr),thisValue)

参数说明:

参数描述
函数参数描述
function(currentValue, index,arr)currentValue必传。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue ,"this" 的值为 "undefined"

**Notice: **

  • some() 不会对空数组进行检测
  • some() 不会改变原始数组。

上代码:

   const arr = [10, 9, 22, 55, 60];
      const arr2 = arr.some(function (icurrentValue, index, arr) {
        console.log(icurrentValue, index, arr);
        return icurrentValue < 30;  //数组中的只要有一个元素的值都要大于30,就直接返回true
      });

1664532696878


filter( )方法的定义与使用:

  • filter( )创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
  • filter( ) 方法用于把Array中的某些元素过滤掉,然后返回剩下的未被过滤掉的元素。

语法:

array.filter(function(currentValue,index,arr), thisValue);

参数说明:

参数描述
函数参数描述
function(currentValue, index,arr)currentValue必传。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。如果省略了 thisValue ,"this" 的值为 "undefined"

返回值:返回数组,包含了符合条件的所有元素.如果明天符合条件的元素则返回空数组

**Notice: **

  • some() 不会对空数组进行检测
  • some() 不会改变原始数组。

上代码:

//过滤某些值
      const arr = [10, 9, 22, 55, 60];
      const newArr = arr.filter((num) => num > 10);
      console.log(newArr); //打印 [22, 55, 60]

      //查找某些值
      const arr = [10, 9, 22, 55, 60];
      const newArr = arr.filter((num) => num === 60);
      console.log(newArr); //打印 [60]

      //返回大于或小于的某些值
      const arr = [10, 9, 22, 55, 60];
      const newArr = arr.filter((num) => num > 10 && num < 55);
      console.log(newArr); //打印 [22]

      // ----------------------
      //   2.数组去重操作:对数组array中所有相同的元素进行去重复操作
      const arr = [8, 8, "s", "s", false, false, 8, 22];
      const newArr = arr.filter((currentValue, index, arr) => {
        return arr.indexOf(currentValue) === index;
      });
      console.log(newArr); //打印 [8, 's', false, 22]

      // 3、数组中保留奇数或者偶数。
      const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
      const newArr = arr.filter((num) => {
        return num % 2 === 0;
      }); //打印[2, 4, 6, 8, 10]
      console.log(newArr);

      //4.把对象数组array中的某个属性取出来存到一个新数组中去
      const arr = [
        { name: "小林", type: "aa" },
        { name: "派大星", type: "bb" },
        { name: "海绵宝宝", type: "cc" },
        { name: "蟹老板", type: "bb" },
      ];
      const newArr = arr.filter((currentValue, index, arr) => {
        return currentValue.type === "bb";
      });

      console.log(newArr);
      //打印 //{name: '派大星', type: 'bb'}
      //{name: '蟹老板', type: 'bb'}

      //5.filter结合find方法
      const arr = [22, 33, 78, 45, 65, 77, 80];
      const oldArr = [12, 22, 65, 88];
      function change() {
        const result = arr.filter((item1) => {
          return !oldArr.find((item2) => {
            return item1 === item2;
          });
        });
        return result;
      }
      const newArr = change();
      console.log(newArr);
      //打印   [33, 78, 45, 77, 80]

find( )方法的定义与使用:

  • find( )方法返回数组中符合测试函数条件的第一个元素.否则返回undefined

  • 一般用于当我需要拿到数据里符合条件的第一条信息,这边就直接上代码吧

  • const student = [
            {
              name: "小丽",
              gdener: "女",
              age: 12,
            },
            {
              name: "李四",
              gdener: "男",
              age: 13,
            },
            {
              name: "张三",
              gdener: "男",
              age: 12,
            },
          ];
          const newStudent = student.find(function (element) {
            return element.age === 12;
          });
          console.log(newStudent); //打印{name: '小丽', gdener: '女', age: 12}
    

findIndex( )方法的定义与使用:

  • findIndex() 方法返回传入一个测试条件(函数)符合条件的数组第一个元素位置。
  • 当数组中的元素在测试条件时返回 true 时, findIndex() 返回符合条件的元素的索引位置注:find()返回的是元素),之后的值不会再调用执行函数。如果没有符合条件的元素返回 -1注:find()返回的是undefined
  • findIndex()方法实现是通过循环遍历查找。应用场景广泛,可以查找大于等于小于,表达式可以随便写。实际上相当于一个for循环,只不过找到了你不需要自己退出。

语法:

array.findIndex(function(currentValue, index, arr), thisValue);

**Notice: **

  • findIndex() 对于空数组,函数是不会执行的。
  • findIndex() 并没有改变数组的原始值。

上代码:

  const student = [
        {
          name: "小丽",
          gdener: "女",
          age: 12,
        },
        {
          name: "李四",
          gdener: "男",
          age: 13,
        },
        {
          name: "张三",
          gdener: "男",
          age: 12,
        },
      ];
      const newStudent = student.findIndex((value) => value.age === 12);
      console.log(newStudent); //打印

forEach( )方法的定义与使用:

  • JavaScript中foreach是用于遍历数组的方法,将遍历到的元素传递给回调函数,遍历的数组不能是空的要有值。
  • forEach方法中的function回调有三个参数: 第一个参数是遍历的数组内容, 第二个参数是对应的数组索引, 第三个参数是数组本身

语法:

[ ].forEach(function(value,index,array){
});

**Notice: **

  • forEach不支持break

  • forEach中使用return无效

上代码:

 const student = [
        {
          name: "小丽",
          gdener: "女",
          age: 12,
        },
        {
          name: "李四",
          gdener: "男",
          age: 13,
        },
        {
          name: "张三",
          gdener: "男",
          age: 12,
        },
      ];
      const newStudent = student.forEach((value,index,item)=>{
        console.log(value,index,item);
      })

1664965606038


includes( )方法的定义与使用:

  • 首先,includes()方法用来判断一个数组是否包含一个指定的值,如果是返回 true,否则false。

语法:

includes(searchElement,fromIndex)
searchElement必选。需要查找的元素值。
fromIndex可选。从该索引处开始查找 searchElement。如果为负值,则按升序从 array.length + fromIndex 的索引开始搜索。默认为 0

上代码:

const student = [1, 2, 3, 4, 5, 6, 7, 8, 9];
      console.log(student.includes(9)); //打印为true

indexOf( )方法的定义与使用:

  • indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。

    如果没有找到匹配的字符串则返回 -1。

语法:

string.indexOf(searchvalue,start)

参数说明

参数描述
searchValue必选。规定需检索的字符串值。
start可选的整数参数。规定在字符串中开始检索的位置。它的合法取值是 0 到 string Object.length - 1。如省略该参数,则将从字符串的首字符开始检索。

**Notice: **

  • indexOf( ) 方法区分大小写。

上代码:

const studenS = ["student","apple","wuhu"]
 console.log(studenS.indexOf("wuhu",0));  //打印2
 console.log(studenS.indexOf("student",1)); //打印-1

isArray( )方法的定义与使用:

  • isArray() 方法用于判断一个对象是否为数组。

    如果对象是数组返回 true,否则返回 false。

语法:

Array.isArray(obj)

参数说明

参数描述
obj必需,要判断的对象。

上代码:

 const student = [
        {
          name: "小丽",
          gdener: "女",
          age: 12,
        },
        {
          name: "李四",
          gdener: "男",
          age: 13,
        },
        {
          name: "张三",
          gdener: "男",
          age: 12,
        },
      ];
      console.log(Array.isArray(student)); //打印true

join( )方法的定义与使用:

  • join()方法就是将array数据中每个元素都转为字符串,用自定义的连接符分割

上代码

 // join('')将数组元素无缝拼接
      const student = Array('s','t','u','d','e','n','t')
      console.log(student.join('')); //打印student

      // join(' ') 将数组元素以空格分割
      const people = Array('student','teacher','principal')
      console.log(people.join(' ')); //打印student teacher principal  这里注意用空格分割

      // join()将数组每个元素都转为字符串,用法等同于toString()
      const number = Array('tt','rr','yy')
      console.log(number);     //打印 ['tt', 'rr', 'yy']
      console.log(number.join());  //打印 tt,rr,yy

map( )方法的定义与使用:

  • map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。

    map() 方法按照原始数组元素顺序依次处理元素。

语法:

array.map(function(currentValue,index,arr), thisValue)

参数说明

参数描述
function(currentValue,index,arr)必须.函数,数组中的每个元素都会执行这个函数
函数参数描述
currentValue必须。当前元素的值
index可选。当前元素的索引值
arr可选。当前元素属于的数组对象
thisValue可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。
如果省略了 thisValue,或者传入 null、undefined,那么回调函数的 this 为全局对象。

**Notice: **

  • map() 不会对空数组进行检测。
  • map() 不会改变原始数组。

上代码:

const student = [
        {
          name: "小丽",
          gdener: "女",
          age: 12,
        },
        {
          name: "李四",
          gdener: "男",
          age: 13,
        },
        {
          name: "张三",
          gdener: "男",
          age: 12,
        },
      ];
      const newArr = student.map((currentValue) => {
        if (currentValue.age === 12) {
          return currentValue.age + 3;
        }
        return currentValue.age;
      });
      console.log(newArr); //打印 [15, 13, 15]

reduce( )方法的定义与使用:

  • reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。

语法:

array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

参数说明

参数描述
function(total, currentValue, currentIndex, arr)必需。用于执行每个数组元素的函数。
函数参数描述
total必需。初始值, 或者计算结束后的返回值。
currentValue必需。当前元素
currentIndex可选。当前元素的索引
arr可选。当前元素所属的数组对象。
initialValue可选。传递给函数的初始值

**Notice: **

  • reduce() 对于空数组是不会执行回调函数的。

上代码:

 const initialValue = 1; //定义了一个初始值
      const number = [1, 3, 5, 7, 9];
      const newNumber = number.reduce(
        (total, currentValue, currentIndex, arrotal) => {
          return total + currentValue;
        },
        initialValue
      );
      console.log(newNumber); //打印26

      const initialValue = 0;
      const student = [
        {
          name: "小丽",
          gdener: "女",
          age: 12,
        },
        {
          name: "李四",
          gdener: "男",
          age: 13,
        },
        {
          name: "张三",
          gdener: "男",
          age: 12,
        },
      ];
      const newArr = student.reduce(
        (total, currentValue, currentIndex, arrotal) => {
          return total + currentValue.age;
        },
        initialValue
      );
      console.log(newArr); //打印37

reverse ( )方法的定义与使用:

  • reverse() 方法用于颠倒数组中元素的顺序。

语法:

array.reverse()

上代码:

const number = [1, 2, 3];
      const newNumber = number.reverse();
      console.log(newNumber); //打印[3, 2, 1]

stort( )方法的定义与使用:

  • sort() 方法用于对数组的元素进行排序。

    排序顺序可以是字母或数字,并按升序或降序。

    默认排序顺序为按字母升序。

语法:

array.sort(sortfunction)

参数说明

参数描述
sortfunction可选。规定排序顺序。必须是函数。

**Notice: **

  • 当数字是按字母顺序排列时"40"将排在"5"前面。

    使用数字排序,你必须通过一个函数作为参数来调用。

    函数指定数字是按照升序还是降序排列。

    这些说起来可能很难理解,你可以通过本页底部实例进一步了解它。

  • 这种方法会改变原始数组!。

上代码:

const points = [40, 100, 1, 5, 25, 10];
      points.sort((a, b) => {
        return a - b;
      });
      console.log(points); //打印  [1, 5, 10, 25, 40, 100]

      const fruits = ["Banana", "Orange", "Apple", "Mango"];
      console.log(fruits.sort()); //打印['Apple', 'Banana', 'Mango', 'Orange']
      console.log(fruits.reverse()); //打印['Orange', 'Mango', 'Banana', 'Apple']