Using an iterative method of JavaScript

Iterative method

Iterative feedback process is repeated activities, its purpose is usually to approach a desired result or goal.
Each of the process is repeated once called "iteration."

forEach :

Because the array is called API arr.forEach ();
forEach => this is called by such a parameter may be omitted;

 		var arr = [4,3,2,1,0];
         arr.forEach(function( item , index , arr){
             // 根据数组有多少项,执行对应次数的匿名函数;
             console.log( item , index , arr);
         }) 
        // 1. 参数 : 函数(函数会被执行数组项数次,并且传入数组的每一项内容,和遍历时的下标,数组本身)
        // 2. 返回值 : undefined ;
        // 3. 作用  : 遍历数组 ,  写的代码量少,以后可能在各种环境配合下使用起来更简便: 

map method

Return value; returns an array of values is composed of each function performed;
may all change, the new array is returned after the change in the array;

var arr = [4,3,2,1,0];
        var res = arr.map( function( item , index , arr){
            // 基本结构使用和forEach没有任何区别;
            // console.log(item , index , arr)
            return parseInt(item * 1.3 * 10) / 10
        })
        console.log(res);

filter method

Return value; as an array after screening.
How to screen: The function returns a value of true, the item is selected when the data in the data array will add this one.
Function return value is false, it indicates that the filter, in which a data array is not added;

 var arr = [4,3,2,1,0];
        var res = arr.filter( function( item , index , arr ){
            // return true;
            // 过滤功能在这里要写条件;
            return item > 2;
        })
        // 函数什么的都不写的情况执行结果都是 undefined , 那么一项内容都不会放进新数组之中;
        console.log(res);

every determination method:

The return value is a Boolean value:
must perform all of the functions are the result of true, the result was to return true;

var arr = [1,2,3,4,5,"hello world"];
        var res = arr.every( function( item , index , arr ){
            return typeof item === "number";
        })  
        console.log(res);

some determination method:

The return value is a Boolean value:
being a function execution result is true, returns the result was true;

var arr = [1,2,"hello world",3,4,5];
        var res = arr.some( function( item ,index ){
            return typeof item === "boolean";
        })
        console.log(res);

to sum up

forEach => designed to iterate; no return value
map => each time you want to change the array using this method; return value is an array;
fileter => The return value is an array of filters;
Every => all determined; The return value is a Boolean value;
some => a determination; return value is a Boolean value;

Released two original articles · won praise 0 · Views 54

Guess you like

Origin blog.csdn.net/weixin_39226765/article/details/104743687