JavaScript array Common Method Code Example Detailed Explanation

  • 2021-08-10 06:41:24
  • OfStack

1.map/reduce

map()

map () is a method of array

Function: Call custom function for every 1 element in array


'use strict';
function pow(x){
return x*x;
}
var arr=[1,2,3,4,5]
var newarray=arr.map(pow)

The callback function of map takes three arguments:

callback (currentValue, index, array) usually only needs the first parameter

PS: The parameter passed in by map () is pow, which is the function object itself

Usually, the custom method called by map only contains 1 parameter

reduce()

reduce () is also a method of array

Function: Starting from the first two elements of the array, as function parameters, pass it into the function to get the result.

As a result, the function is called again with the next array element until the end of the array

[x1, x2, x3, x4].reduce(f) = f(f(f(x1, x2), x3), x4)
PS: Usually the custom method called by reduce () contains only two parameters

2. filter (screening)

Function: Filter out some elements of Array, and then return the remaining elements.

Like map (), filter () of Array also accepts a function. Unlike map (), filter () applies the passed-in function to each element in turn, and then decides whether to keep or discard the element depending on whether the return value is true or false.

//Remove empty strings


var arr = ['A', '', 'B', null, undefined, 'C', ' '];
var r = arr.filter(function (s) {
  return s && s.trim(); //  Note: IE9 The following versions do not have trim() Method 
});
r; // ['A', 'B', 'C']

Callback function

Usually we only use the first parameter, which represents an element of Array. The callback function can also take two other parameters, representing the position of the element and the array itself:


var arr = ['A', 'B', 'C'];
var r = arr.filter(function (element, index, self) {
  console.log(element); //  Print in turn 'A', 'B', 'C'
  console.log(index); //  Print in turn 0, 1, 2
  console.log(self); // self Is the variable arr
  return true;
});

Filter prime numbers:


function get_primes(arr){
if(elem===1){
return false;
}
for(var i=2;i<=elem/2;i++){
if(elem%i==0)
{
return false;
}
}
return true;
});
return x;
}

PS: The key is to implement a "filter" function correctly

3. sort (Sort)

The default sort will convert all elements to String in the sort, and sort according to the ASCII value of one element (non-decreasing) (TimSort algorithm)

Pairwise comparison, when the callback function returns a value greater than 0, exchange element values

Custom numeric sorting


'use strict' 
var arr=[10,20,1,2];
arr.sort(function(x,y){
	if (x < y) {
    return -1;
  }
  if (x > y) {
    return 1;
  }
  return 0;
});
console.log(arr); // [1, 2, 10, 20]

Numbers are arranged in reverse order


var arr = [10, 20, 1, 2];
arr.sort(function (x, y) {
  if (x < y) {
    return 1;
  }
  if (x > y) {
    return -1;
  }
  return 0;
}); // [20, 10, 2, 1]

4. Other Array methods

every () and some ()

Function: You can determine whether all elements of the array meet the test conditions (provided by function)

every () returns true when all are satisfied, and false when one is not satisfied, and the detection is terminated

some () returns false when all are not satisfied, and true when one is satisfied

find()

Function: Find the first eligible element

Find the first element that meets the criteria, and return this element if it is found, otherwise, return undefined

findindex()

Function: Find the index of the first eligible element

Find the first element that matches the criteria. If you find this element, you will return its index. If you don't find it, you will return-1

forEach()

Function: Commonly used to traverse arrays

(Similar to map) passes each element of the array into the function in turn, but does not return a new array.

Function as the return value
One more function is defined in the function, and the return value is the function defined in it

Calling a function as a function of return value returns 1 new function for each call, even if the same parameters are passed in


function lazy_sum(arr) {
  var sum = function () {
    return arr.reduce(function (x, y) {
      return x + y;
    });
  }
  return sum;
}
// The summation function is returned 
var f = lazy_sum([1, 2, 3, 4, 5]); // function sum()
f(); // 15  Called at this time , Before calculating 

The function sum is defined in the function lazy_sum, and the internal function sum can reference the parameters and local variables of the external function lazy_sum. When lazy_sum returns the function sum, the related parameters and variables are stored in the returned function. This program structure called "closure (Closure)" has great power.

Closure (stupid) (spit rainbow)

All functions that have access to variables in the scope of another function are closures.

The function inside the function will change with the externally defined function

PS: Because the return value is a function, use parentheses when calling

One thing to keep in mind when returning closures is that the return function should not refer to any loop variables or variables that will change later.

What if 1 must reference a loop variable? The method is to create another function, and bind the current value of the loop variable with the parameters of this function. No matter how the loop variable changes later, the values bound to the function parameters remain unchanged:

Arrow function (= > ) (Strong)
(Parameter...) = > {Function body} is equivalent to function (parameter...) {Function body}

When 1 object is returned, the function body braces are surrounded by braces

x= > ({foo:x})

this

The this inside the arrow function is the lexical scope, which is determined by the context


var obj = {
  birth: 1990,
  getAge: function () {
    var b = this.birth; // 1990
    var fn = () => new Date().getFullYear() - this.birth; // this Point obj Object 
    return fn();
  }
};
obj.getAge(); // 25

The arrow function completely fixes the this pointing, and this always points to the lexical scope, that is, the outer call obj

generator (Generator)

ES6 Introduces the same name function of Python

The writing is similar to the function, except that * is added after function, and the value can be returned multiple times through yield, and the value can also be returned through return

The function is executed if it does not encounter an return statement (if there is no return at the end of the function, it is implicit return undefined;) Control cannot be surrendered to the called code.


function* (x){
yield x
}
function* fib(max) {
  var
    t,
    a = 0,
    b = 1,
    n = 0;
  while (n < max) {
    yield a;
    [a, b] = [b, a + b];
    n ++;
  }
  return;
}
fib(5); // fib {[[GeneratorStatus]]: "suspended", [[GeneratorReceiver]]: Window}

Calling an generator directly is not the same as calling a function. fib (5) just creates an generator object and has not yet executed it.

There are two methods for calling an generator object,

1 is to constantly call the next () method of the generator object: The next () method executes the code of generator, and then, every time yield x is encountered; It returns 1 object {value: x, done: true/false}, and then "pauses". The returned value is the return value of yield, and done indicates whether the execution of this generator has ended. If done is true, value is the return value of return. When done is true, the generator object is completely executed, so don't continue calling next () `.


var f = fib(5);
f.next(); // {value: 0, done: false}
f.next(); // {value: 1, done: false}
f.next(); // {value: 1, done: false}
f.next(); // {value: 2, done: false}
f.next(); // {value: 3, done: false}
f.next(); // {value: undefined, done: true}

The second method is to iterate the generator object directly with the for... of loop, which does not require us to judge done ourselves:


var arr = ['A', '', 'B', null, undefined, 'C', ' '];
var r = arr.filter(function (s) {
  return s && s.trim(); //  Note: IE9 The following versions do not have trim() Method 
});
r; // ['A', 'B', 'C']
0

Another great benefit of generator is that it turns asynchronous callback code into "synchronous" code. This benefit will not be realized until you learn AJAX later.


var arr = ['A', '', 'B', null, undefined, 'C', ' '];
var r = arr.filter(function (s) {
  return s && s.trim(); //  Note: IE9 The following versions do not have trim() Method 
});
r; // ['A', 'B', 'C']
1

Code that appears to be synchronous actually executes asynchronously.


Related articles: