zoukankan      html  css  js  c++  java
  • 数组循环的各种方法的区别

    1. forEach

    不能使用return中止循环

    var arr=[1,3,2,4];
    arr.forEach((item,index)=>{
    console.log(item);//1 3 2 4,每一项都打印出来了
    return;
    })

    使用break中止循环会报错

    var arr=[1,3,2,4];
    arr.forEach((item,index)=>{
    console.log(item);
    break;//报错
    })

    2.map

    map同forEach,但是map可以使用return,改变每一项的值,forEach则没有返回值

    var arr = [1, 3, 2, 4];
    var newArr = arr.map((item, index) => {
    return item*2;
    })
    console.log(newArr);
    //[2, 6, 4, 8],
    不仅有返回值,还可以进行计算

    var arr = [1, 3, 2, 4];
    var newArr = arr.forEach((item, index) => {
    return item;
    })
    console.log(newArr);//undefined,返回值




    原文链接:https://blog.csdn.net/luoyumeiluoyumei/article/details/80876274

    1. forEach

    不能使用return中止循环

    var arr=[1,3,2,4];
    arr.forEach((item,index)=>{
    console.log(item);//1 3 2 4,每一项都打印出来了
    return;
    })

    使用break中止循环会报错

    var arr=[1,3,2,4];
    arr.forEach((item,index)=>{
    console.log(item);
    break;//报错
    })

    2.map

    map同forEach,但是map可以使用return,改变每一项的值,forEach则没有返回值

    var arr = [1, 3, 2, 4];
    var newArr = arr.map((item, index) => {
    return item*2;
    })
    console.log(newArr);
    //[2, 6, 4, 8],
    不仅有返回值,还可以进行计算

    var arr = [1, 3, 2, 4];
    var newArr = arr.forEach((item, index) => {
    return item;
    })
    console.log(newArr);//undefined,返回值




    原文链接:https://blog.csdn.net/luoyumeiluoyumei/article/details/80876274

  • 相关阅读:
    unix网络编程源码编译问题
    ubuntu15.04下安装docker
    hexo博客的相关配置
    hexo的jacman主题配置
    使用github和hexo搭建静态博客
    操作系统简单认识
    github for windows安装以及教程
    编译原理第五单元习题
    python3入门之列表和元组
    Python3入门之软件安装
  • 原文地址:https://www.cnblogs.com/yadi001/p/12981619.html
Copyright © 2011-2022 走看看