JS数组的高级方法

JS数组的高级方法有:

1:forEach( ) 循环遍历数组

2:every( ) 遍历数组,返回值遇到false时遍历终止 相比于forEach()多了一个return false

3:map( ) 修改并返回新的数组

4:find( ) 找到数组的第一个元素

5:findIndex( ) 找到数组的第一个元素的下标

6:some( ) 找到数组的第一个元素返回值为找到为true或找不到为false

7:flatMap( ) 把数组里面的二维数组拉平成为一个一维数组

8:reduce( ) 数组求和运算

9:filter( ) 数组过滤器

直接上演示案例:

<!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>数组的高级方法</title>
  </head>
  <body>
    <script>
      var array = [1, 2, 3];

      // forEach()循环遍历数组
      // 数组名.forEach(function (变量名) {});
      array.forEach(function (item) {
        console.log(item);
      });

      // map()修改并返回新的数组
      // var 新数组名 = 数组名.map(function ([变量]) { return 参数 修改的全部数组或变量名的条件 修改部分数组 });
      var newArray1 = array.map(function () {
        return 1;
      });
      console.log(newArray1);

      var newArray2 = array.map(function (item) {
        return (item = item > 2 ? item : 5);
      });
      console.log(newArray2);

      // find()找到数组的第一个元素
      // 数组名.find(function(变量名){ return 变量名的条件 })
      console.log(
        array.find(function (item) {
          return item == 1;
        })
      );

      // findIndex()找到数组的第一个元素的下标
      // 数组名.findIndex(function(变量名){ return 变量名的条件 })
      console.log(
        array.findIndex(function (item) {
          return item == 1;
        })
      );

      // some()找到数组的第一个元素返回值为找到为true或找不到为false
      // 数组名.some(function(变量名){ return 变量名的条件 })
      console.log(
        array.some(function (item) {
          return item == 1;
        })
      );

      // every()遍历数组,返回值遇到false时遍历终止 相比于forEach()多了一个return false
      // 数组名.every(function (变量名) { [return false;] });
      array.every(function (item) {
        console.log(item);
        return false;
      });

      // flatMap()把数组里面的二维数组拉平成为一个一维数组
      // 数组名.flatMap(function(变量名){ return 变量名 })
      var array2 = [1, 2, 3, [1], [2]];
      console.log(
        array2.flatMap(function (item) {
          return item;
        })
      );

      // reduce()数组求和运算
      // 数组名.reduce(function (累加变量名,变量名){ return 累加变量名 + 变量名 })
      console.log(
        array.reduce(function (sum, item) {
          return (sum += item);
        })
      );

      // filter()数组过滤器
      // 数组名.filter(function (变量名){ return 变量名的条件 })
      console.log(
        array.filter(function (item) {
          return item > 5 ? item : 10;
        })
      );
    </script>
  </body>
</html>

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值