An iterative approach to arrays in JavaScript

Source: Internet
Author: User

//Both accept 3 parameters, respectively: value, position in array, array object itself
var num = [2, 1, 5, 4, 2, 1, 6, 8, 19];
//every: Returns TRUE if each entry returns True
var a= num.every (function (Item,index,array) {
Return item>5
});
Console.log (a);
   //False

//filter: Returns an array of true items
var b= num.filter (function (Item,index,array) {
Return item>5
});
Console.log (b);
   //[6, 8, +]

//foreach: no return value
var c= num.foreach (function (Item,index,array) {
Return item>5
});
Console.log (c);
   //undefined

//map: Returns an array that consists of return values
var d= num.map (function (Item,index,array) {
Return ' +index+ ' item: ' +item;
});
Console.log (d);
//["No. 0 2", "1th Item 1", "2nd Item 5", "3rd Item 4", "4th Item 2", "5th Item 1", "6th Item 6", "7th Item 8", "8th item"]

//some: Returns True if any of the entries returns true
var e= num.some (function (Item,index,array) {
Return item>5
});
Console.log (e);
  //True

  

=================== Merge method
  
Reduce and reduceright all items of the iterated algebraic group, returning a final value
    reduce is the same as Reducerright, an iteration from the beginning, and an iteration from the back
Pass in four parameters: the previous item, the current item, the index of the item, the array itself
The previous prev is the result of the previous function
var sum=num.reduce (function (Prev,cur,index,array) {
if (index==1) {
Return ' +index+ ': ' +cur+ '; ';
}
Return prev+ ' +index+ ': ' +cur+ '; ';
});
Console.log (sum);
1th Item: 1, 2nd item: 5, 3rd item: 4, 4th item: 2; 5th item: 1; 6th entry: 6; 7th entry: 8; 8th: 19;

An iterative approach to arrays in JavaScript

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.