JavaScript Basics (vi) Array method closure

Source: Internet
Author: User
Tags closure pow javascript array

A method that binds a function in an object called this object.
In JavaScript, the object is defined as such;
var Guagua = {
Name: ' Melon ',
birth:1990
};
However, if we bind a function to the melon, we can do more things.
var Guagua = {
Name: ' Melon ',
birth:1990,
Age:function () {
var y = new Date (). getFullYear ();
return Y-this.birth;
}
}
Guagua.age; function Guagua.age ()
Xguagua.age (); This year the call is 25, and next year the call becomes 26.

Apply
Although in a separate function call, depending on whether it is strict mode, this point points to undefined or window, but we can also control the point of this.
To specify which object this function is pointing to, you can use the function's own method, he receives two parameters, the first one is the this variable that needs to be bound,
The second argument is an array, which represents the parameters of the function itself.
Fix Getage () call with apply:
function Getage () {
var y = new Date (). getFullYear ();
return Y-this.birth;
}

var Guagua = {
Name: ' Xiaoming ',
birth:1990,
Age:getage
};
Guagua.age (); 25
Getage.apply (xiaoming,[]); The this pointer to the Xiaoming parameter is empty.

Another method similar to apply () is call (), the only difference being:
Apply () package the parameters into an array and then pass in;
Call () passes parameters sequentially.
For example, call Math.max (3, 5, 4), respectively, with apply () and calls () to achieve the following
Math.max.apply (null,[3,5,4]); 5
Math.max.call (null,3,5,4); 5
For normal function calls, we usually bind this to null.

Map
Because of the map () FANGF Dingyi zai JavaScript Array, we call array's map () method, passing in our own function, we get a new array
function Pow (x) {
return x * x;
}
var arr = [1,2,3,4,5,6,7,8,9];
Arr.map (POW); [1,4,9,16,25,36,49,64,81]
Map () The parameter passed in is the POW, which is the function object itself.

Reduce
In view of the coping of reduce, the reduce () of the array takes a function as the [x1,x2,x3 ...] in this array. , this function must receive two parameters,
Redyce () The result continues and the next element of the sequence is accumulated, the effect is.
[X1,x2,x3,x4].reduce (f) = f (f (f (x1,x2), x3), x4)
For example, to sum an array, you can use reduce to achieve:
var arr = [1, 3, 5, 7, 9];
Arr.reduce (function (x, y) {
return x + y;
}); 25
converting [1, 3, 5, 7, 9] to an integer 13579,reduce () can also come in handy:
var arr = [1, 3, 5, 7, 9];
Arr.reduce (function (x, y) {
return x * ten + y;
}); 13579

Filter
Filter is also a common operation, it is used to filter out some elements of the array, and then return the remaining elements.
Like map (), the filter () of the array also receives a function. Unlike map (), filter () applies the incoming function to each element sequentially,

The element is then persisted or discarded depending on whether the return value is true or false.
In an array, delete even numbers, keep only odd numbers, and you can write:
var arr = [1,2,4,5,6,9,10,15];
var r = arr.filter (function (x) {
return x% 2!==0;
});
R://[1,5,9,15]
To delete an empty string in an array, you can write:
var arr = [' A ', ' ', ' B ', null,undefined, ' C ', '];
var r = Arr.flter (function (s) {
return s && s.trim (); Note: The following versions of IE9 do not have the trim () method
})
R://[' A ', ' B ', ' C ']
The key is to implement a "filter" function correctly by using the filter () as a high-order function.

Sort
The sort () method of the JavaScript array is used for sorting, but the sorting results may surprise you:
Looks like a normal result.
[' Google ', ' Apple ', ' Microsoft '].sort (); [' Apple ', ' Google ', ' Microsoft '];
Apple is at the end of the line
[10,20,1,2].sort (); [1,10,2,20]
The second sort puts Apple in the last place because the strings are sorted according to the ASCII code, and the ASCII code for the lowercase a is after the uppercase letters.

To sort by numerical size, we can write this:
var arr = [10,20,1,2]
Arr.sort (function (x, y) {
if (x < y) {
return 1;
}
if (x > Y) {
return 1;
}
return 0;
})//[1,2,10,20]

If you want to sort in reverse order, we can put the large number in front:
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]

  

We propose that the sort should be ignored in case of alphabetical order
var arr = [' Google ', ' apple ', ' Microsoft '];
Arr.sort (function (S1,S2) {
X1 = S1.touppercase ();
x2 = S2.touppercase ();
if (X1 < x2) {
return-1;
}
if (X1 > x2) {
return 1;
}
return 0;
}); [' Apple ', ' Google ', ' Microsoft ']
Ignoring the case to compare two strings is actually the first to capitalize the strings (or all lowercase) before comparing them.

The sort () method modifies the array directly, and the result is still the current array:
var a1 = [' B ', ' A ', ' C '];
var a2 = A1.sort ();
A1; [' A ', ' B ', ' C ']
A2; [' A ', ' B ', ' C ']
A1 = = = A2; True, A1 and A2 are the same object

The closure function as the return value
The high-stage function can also return a function as a result value, in addition to the ability to accept functions as parameters.
function sum (arr) {
Return Arr.reduce (function (x, y) {
return x + y;
});
}
SUM ([1,2,3,4,5]); 15

But what if you don't need to sum it right away, but in the later code, and then calculate it as needed? You can return the SUM function without returning the result of the summation!
function Lazy_sum (arr) {
var sum = function () {
Return Arr.reduce (function (x, y) {
return x + y;
})
}

return sum;

When we call Lazy_sum (), we return the SUM function instead of summing the result:
var f = lazy_sum ([1,2,3,4,5]); function sum ();
The result of summing is really calculated when the function f is called.
f (); 15
When we call Lazy_sum (), each call will return a new function, even if the same parameters are passed in:
var f1 = Lazy_sum ([1,2,3,4,5]);
var F2 = Lazy_sum ([1,2,3,4,5])
F1 = = = F2; False

Closed Package
The returned function references the local variable within its definition arr, all, saying that a function is returned with a function whose internal variables are also referenced by new illusions, so it is easy to close the packet.
function count () {
var arr = [];
For (var i= 1; I <=3; i++) {
Arr.push (function () {
return i * i;
})
}
return arr;
}
var results = count ();
var f1 = results[0];
var F2 = results[1];
var f3 = results[2];

You might think that calling F1 (), F2 (), and F3 () results should be 1,4,9, but the actual result is:
F1 (); 16
F2 (); 16
F3 (); 16

One thing to keep in mind when returning closures is that the return function does not refer to any loop variables, or to subsequent variables that change.

function count () {
var arr = [];
for (var i=1; I <=3; i++) {
Arr.push ((function (n) {
return function () {
return n * N;
}
}) (i));
}

  

Note Here is a syntax for creating an anonymous function and executing it immediately:
(function (x) {
return x * x;
}) (3); 9

return arr;
}

var results = count ();
var f1 = results[0];
var F2 = results[1];
var f3 = results[2];
F1 (); 1
F2 (); 4
F3 ();//9

In the absence of a class mechanism, only the language of the function, with closures, can also encapsulate a private variable. We create a counter with javascript:
function Create_counter (initial) {
var x = inintial | | 0;
return {
Inc:function () {
x +=1;
return x;
}
}
}

It used to look like this:
var C1 = Create_counter ();
C1.inc (); 1
C1.inc ();//2
C1.inc ();//3
var C2 = Create_counter (10);
C2.inc (); 11
C2.inc (); 12
C2.inc ();//13

Closures can also turn multi-parameter functions into single-parameter functions.
function Make_pow (n) {
return function (x) {
Return Math.pow (X,n);
}
}
Create two new functions.
var pow2 = Make_pow (2);
var pow3 = Make_pow (3);
Pow2 (5); 25
POW3 (7); 343

JavaScript Basics (vi) Array method closure

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.