JavaScript Note 6-new Array method

Source: Internet
Author: User
Tags mul pow



Seven. ECMAScript5 A new approach to arrays
1.forEach (): iterates through the array and invokes the incoming function for each element;
Example:


1 var a = [1,2,3];
   2 var sum = 0;
   3 // Pass a parameter
   4 a.forEach (function (v) {
   5 sum + = v;
   6});
   7 console.log (sum); // 6
   8 // Pass three parameters (element value, index, array itself)
   9 a.forEach (function (v, i, a) {
  10 a [i] = v + 1; // Increment 1 for each element of the array
  11})
  12 console.log (a); // [2,3,4] 





2.map (): Each element of the array that invokes the function is passed into the specified function, and the new array after the operation is returned;
Note: The function does not modify the original array.
Example:


 
 
 1 var a = [1,2,3];
  2 var b = a.map(function(x){
  3      return x*x;
  4  })
  5  console.log(b);//[1,4,9]






3.filter (): Each element of the array that invokes the function is passed into the specified function for determination, and if it is determined to be true, it is Returned. eventually returns a collection of elements that match the specified condition (function) (the collection is a subset of the original Array)
Note: This function skips missing elements in a sparse array, always returns a dense array, which can be used to compress sparse arrays.
Example 1:


 
 
 1  var a = [1,2,3];
  2      var c = a.filter(function(x){
  3          return x<3;
  4      })
  5      console.log(c);

Example 2:
1 var a = [, 1, null, 3,4,,];
   2 console.log (a.length); // 6
   3 var dense = a.filter (function () {
   4 return true; // filter out undefined
   5});
   6 console.log (dense); // [1, null, 3,4]
   7 console.log (a); // Array (6) […, 1, null, 3, 4] unchanged the original array
   8 var c = a.filter (function (x) {
   9 return x! = Undefined && x! = Null;
  10});
  11 console.log (c); // Array (3) [1, 3, 4] 





4.every (): iterates over each element that invokes the method array, determines whether the specified condition (function) is met, returns true if all matches, and returns True when an empty array is called;
Some (): iterates over each element that invokes the method array, determines whether the specified condition (function) is met, returns True if there is a match, and returns False when an empty array is called;
Example 1:


1 var a = [1,2,3,4,5];
   2 var b = a.every (function (x) {
   3 return x> 0; // determine if all elements are greater than 0
   4});
   5 console.log (b); // true
   6 var c = a.some (function (x) {
   7 return x <4; // determine if any element is less than 4
   8      });
   9 console.log (c); // true 

Example 2: empty array invocation
 
 
1 var d = [];
  2      console.log(d.every(function(x){
  3          return x;
  4      }));//true
  5      console.log(d.some(function(x){
  6          return x;
  7      }));//false





5.reduce () and Reduceright ()
Creates a single value by combining the array elements with the specified function. specifies that a function requires two values (the first is a function that performs a degenerate operation; the second (optional) is the initial value passed to the Function)
Note: 1) When there is no second argument, the function invokes the first element of the array as the initial value, and if the array is an empty array the "type error" exception is reported;
2) if the array has only one element, and the second argument is not provided, the function is not called and only the unique element is returned;
Example 1:


1 var a = [1,2,3,4,5];
   2 // summation
   3 var sum = a.reduce (function (x, y) {
   4 return x + y;
   5}, 0);
   6 console.log (sum); // 15
   7 // Quadrature
   8 var mul = a.reduce (function (x, y) {
   9 return x * y;
  10}, 1)
  11 console.log (mul); // 120
  12 // Find the maximum
  13 var max = a.reduce (function (x, y) {
  14 return x> y? X: y;
  15}, 0)
  16 console.log (max); // 5 

Example 2: Power operation
 
 
 1 var a = [2,3];
  2 var big = a.reduceRight(function(x,y){
  3      return Math.pow(y,x);
  4  });
  5  console.log(big);//2^3=8
  6 
  7 var big1 = a.reduceRight(function(x,y){
  8      return Math.pow(x,y);
  9  });
 10  console.log(big1);//3^2=9
 11 








6.indexOf () and LastIndexOf ()
Returns the element of the given index value, lastIndexOf () searches from right to left, or 1 if not found;
Note: The function can receive two parameters, the first parameter is the index to search, the second is the location to start the search (optional), and two parameters are not functions;
Example: define a function, Find all occurrences of x in an array, and return an array containing all the indexes


 
1 function findall (a, x) {
   2 var results = []; // Define an empty array to receive the index value of x
   3 len = a.length; // The maximum length of the search
   4 pos = 0; // where to start searching
   5 while (pos <len) {
   6 pos = a.indexOf (x, pos); // Search x from pos
   7 if (pos === -1) {
   8 break; // return if not found
   9         }
  10 results.push (pos); // store the index value
  11 pos = pos + 1;
  12}
  13 return results;
  14}
  15 tests
  16 var a = [1,2,3,2,4];
  17 console.log (findall (a, 2)); // Array (2) [1, 3]





Eight. determine whether the array
Array.isarray (): Determines whether the array type is true;



Nine. string can be used as a read-only array
You can use square brackets ([]) to access a single character;
can also function Charat () method
Example:


 1var s = test;  2 s.charat (0);  "t" 3 s[0];  "t"





Ten: Requirements: Convert a string composed entirely of numbers into a numeric type, such as "1345" to 1345
Law One:


1 ‘use strict’;
   2 function string2int (s) {
   3 // Convert s to string array
   4 var str = s.split (‘‘);
   5 // Call map () to convert the array of strings to an array of numbers
   6 var arr = str.map (function (x) {
   7 // Character -0 becomes a number
   8 return x-0;
   9      })
  10 // Call reduce () to convert the array of numbers to int
  11 var res = arr.reduce (function (x, y) {
  12 return x * 10 + y;
  13})
  14 // Return result
  15 return res;
  16} 

Law Ii:
1 ‘use strict’;
   2 var b = "1345";
   3 // split (): convert a string to an array of character types
   4 var c = b.split (‘‘);
   5 // Subtract from 0 to convert character type to numeric type
   6 var d = [];
   7 for (var i = 0; i <c.length; i ++) {
   8 d [i] = c [i] -0;
   9  }
  10 // Convert to integer
  11 var e = d.reduce (function (x, y) {
  12 return x * 10 + y;
  13})
  14 console.log (e); 





JavaScript Note 6-new Array method


Related Article

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.