• js 中的五种迭代方法


    ECMAScript 为数组定义了五个迭代方法。
    每个方法都接收两个参数:要在每一项上运行的函数和(可选的)运行该函数的作用域对象——影响this的值。
    传入这些方法中的函数会接收三个参数:数组项的值、该项在数组中的位置和数组对象本省。
    根据使用的方法不同,这个函数执行后的返回值可能会也可能不会影响方法的返回值。
    以下是这五个迭代方法的作用。
    
    1、every(); 
    对数组中的每一项运行给定函数,如果该函数对每一项都返回true,则返回true。 2、some();
    对数组的每一项运行给定函数,如果该函数对任一项返回true,则返回true。
     var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
     var everyResult = numbers.every(function(item, index, array){
         return (item > 3);
     })
     console.log(everyResult);    //false
        
     var someResult = numbers.some(function(item, index, array) {
         return (item > 3);
     })
     console.log(someResult);    //true
    3、filter(); 
    对数组中的每一项运行给定函数,返回改函数会返回true的项组成的数组。
    var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    var filterResult = numbers.filter(function(item, index, array) {
        return (item > 3);
    })
    console.log(filterResult);    //[4, 5, 4]
    4、map(); 
    对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组。
    var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    var mapResult = numbers.map(function(item, index, array) {
        return item * 2;
    })
    console.log(mapResult);    //[2, 4, 6, 8, 10, 8, 6, 4, 2]
    5、forEach(); 
    对数组中的每一项运行给定的函数,该方法没有返回值,本质上与使用for循环迭代数组一样。
    var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
    numbers.forEach(function(item, index, array) {
       //执行某些操作
    })

    原文路径:https://segmentfault.com/a/1190000009940387

  • 相关阅读:
    {C#}{GDI+}各种C#,GDI+的资料
    {Reship}{C#}{GDI+}GDI+画笔,线,区域类型
    {VS2010C#}{WinForm}{ActiveX}VS2010C#开发基于WinForm的ActiveX控件
    {matlab}取二值图像centroid几种方法性能比较
    {vlFeat}{Matlab}Linux中matlab的vlFeat配置
    {Links}{Matting}{Saliency Detection}{Superpixel}Source links
    {Reship}{Matting}Image Matting
    javascript中的装箱和拆箱操作
    javascript中的垃圾回收
    javascript中的类方法、构造方法、原型方法的对比
  • 原文地址:https://www.cnblogs.com/lcspring/p/11167165.html
Copyright © 2020-2023  润新知