Learn array iteration | traversal

<Growth essays front end of a kindergarten class size, mistakes and shortcomings, it looks great cattle criticism advice, thank you!>

Common Array iterative method:

map / filter / forEach / every / some

  1. map 返回 每次函数调用返回的结果 组成的数组

  2. filter 返回 该函数 会返回true的项 组成的数组

  3. forEach 无返回值 ES5 method

  4. every 数组所有项都返回true 则返回true,类似&& 一旦有一个不符合条件,则停止迭代

  5. some 函数对数组里面有一项返回true 则返回true,类似|| 不停的迭代找符合条件的值,一旦找到,则停止迭代


 

Code demonstrates:

var arr = [1,2,3,4,5];
  console.log(arr.map((item,index,arr)=>{
    console.log('map: ', item, index ,arr);
    return item>2 })); 1. // 返回[false,false,true,true,true] console.log(arr.filter(function(item,index,arr){ console.log('filter: ', item,index,arr); return item>2; })); 2. // 返回 [3,4,5]  ​ console.log(arr.forEach(function(item,index,arr){ console.log('foreach: ', item,index,arr); return item>2; })); 3. // forEach无返回值  ​ console.log(arr.every((item,index,arr) => { console.log('every: ', item, index, arr); return item>2; })); 4.// returns false, print it again every:
 ​ console.log(arr.some((item, index, arr) => { console.log('some: ', item, index, arr); return item>2; })); 5. // 返回true,打印3遍some:


> demo1: forEach
arr.forEach (function (value, index) { 
// First parameter: the array element 
// Second parameter: indexed array element }) 
// for loop array traversal corresponds to no return value 
/ * --- ---------------------------------------------- * / 
// forEach 
// 1. E is a capital letter 
var ARR = [ 'a', 'B', 'C' ]; 
// syntax: array name .forEach (callback) 
arr.forEach (function (value) {  Console. log (value);  });  // 2. array element value is the first parameter, the array index is the second parameter  arr.forEach (function (V, I) {  the console.log ( 'first' + i + 'value of the element is' + V);})


> demo2: filter
ARR = var [12 is, 66,. 4, 88,. 3,. 7 ]; 
var = newArr arr.filter (function (value, index) { 
// First parameter: the array element 
// Second parameter: the array element index 
return value> = 20 is ; 
}); 
the console.log (newArr); // [66,88] // return value is an array of new
> demo3: some 
// some find out whether there are elements in the array satisfies the condition 
var ARR = [10, 30,. 4 ]; 
var = arr.some In Flag (function (value, index) { 
// First parameter: the array element 
// Parameter Second: indexed array element 
return value <. 3 ; 
}); 
the console.log (in Flag); // return value is a Boolean value, as long as the condition is found to immediately terminate the loop element

 

 

Guess you like

Origin www.cnblogs.com/carrot-cc/p/11106818.html