javascript iteration method

every() method Runs the given function for ea...
every() method
some() method
filter() method
map() method
forEach() method

every() method

Runs the given function for each item in the array, and returns true if it returns true for each item

let number = [1,2,3,4,5,6,7,8,9,10,11,12,1,31,21];

Example 1:

let everyResult = number.every(function(item,index,array){ console.log('item:'+item); //item:1 console.log('index:'+index); //index:0 console.log('array:'+array); //array:1,2,3,4,5,6,7,8,9,10,11,12,1,31,21 }); console.log(everyResult); // false

Example 2:

let everyResult2 = number.every(function(item,index,array){ return item>2; }); console.log(everyResult2); // false

Example 3:

let everyResult3 = number.every(function(item,index,array){ return item>=1; }); console.log(everyResult3); // true

some() method

Runs the given function for each item in the array, and returns true if it returns true for any item.

Example 1:

let someResult = number.some(function(item,index,array){ console.log('item:'+item); //Output every item console.log('index:'+index); console.log('array:'+array); }); console.log(someResult); // false

Example 2:

let someResult2 = number.some(function(item,index,array){ return item>2; }); console.log(someResult2); // true

Example 3:

let someResult3 = number.some(function(item,index,array){ return item<0; }); console.log(someResult3); // false

filter() method

Run the given function for each item in the array, and the return function returns an array of items that are true.

Example 1:

let filetResult = number.filter(function(item,index,array){ console.log('item:'+item); console.log('index:'+index); console.log('array:'+array);//Loop out all items }); console.log(filetResult);// Empty array

Example 2:

let filetResult2 = number.filter(function(item,index,array){ return item>4; }); console.log(filetResult2);// (10) [5, 6, 7, 8, 9, 10, 11, 12, 31, 21]

Example 3:

let filetResult3 = number.filter(function(item,index,array){ return item<1; }); console.log(filetResult3);//Empty array

map() method

Run the given function for each item in the array, and return the array composed of the results of each function call.

example:

let mapResult = number.map(function(item,index,array){ return item*2; }); console.log(mapResult);//(15) [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 2, 62, 42]

forEach() method

Runs the given function for each item in the array with no return value.

numbers.forEach(function(item,index,array){ //Do something });

27 May 2020, 11:50 | Views: 3916

Add new comment

For adding a comment, please log in
or create account

0 comments