JavaScript Full Learning (middle height)

Source: Internet
Author: User
Tags pow shuffle

1. When a block of code is try { ... } wrapped, it means that some errors may occur during the execution of the Code, and in the event of an error, the subsequent code is no longer executed and jumps to the catch block instead. catch (e) { ... }the code of the package is the error-handling code, and the variable e represents the error caught.

Finally, there is no mistake, it finally will be executed.

catchand finally can not have to appear

  throwThe statement actively throws an error, allowing the execution process to jump directly to the catch block.

When we catch errors with catch, be sure to write error-handling statements, even if you just print console.log the error, and don't do nothing.

If an error occurs inside a function that itself is not captured, the error is thrown into the outer calling function, and if the outer function is not captured, the error will always be thrown upward along the function call chain until it is captured by the JavaScript engine, and the code terminates execution.

2.

function Printtime () {    thrownew  Error ();} Try {    );    Console.log (' Done 'catch  (e) {    alert (' error ');}

This code does not eject the error because setTimeout() the function passed in is printTime not executed immediately when the function is called! Immediately thereafter, the JavaScript engine continues to execute console.log(‘done‘); the statement, and no error occurs at this time. An error occurred until 1 seconds after the function was executed, printTime but the printTime outer code could not be captured except for catching an error inside the function. (all functions are completed and 1000MS functions are processed)

Therefore, the asynchronous code is involved and cannot be captured at the time of the call because the callback function was not executed at the time of the capture.

Similarly, when we are dealing with an event, the error of the event handler cannot be captured at the code where the event is bound .

3.underscore.js

Implementation map() action (can be used for object):

// [1, 4, 9] // [' a=1 ', ' b=2 ', ' c=3 ']

4.every/some

' Use strict '; // are all elements greater than 0?  //  false/ / at least one element is greater than 0?  //  true

5.max/min

' Use strict '; var arr = [3, 5, 7, 9//  9//  3//  The empty collection returns-infinity and Infinity, so the collection must be judged not to be empty:_.max ([])-infinity_.min ([]) Infinity

If the collection is object, max() and min() only works on value, ignore key:

// 3

6. The groupBy() elements of the collection are categorized by key, and key is returned by the function passed in:

' Use strict ';varscores = [20, 81, 75, 40, 91, 59, 77, 66, 72, 88, 99];varGroups = _.groupby (scores,function(x) {if(X < 60) {        returnC; } Else if(X < 80) {        returnB; } Else {        returnA; }});//Results:// {//A: [Bayi , the ","),//B: [A.]//C: [+]// }

7.shuffle/sample

shuffle()Shuffle an algorithm randomly to shuffle a set:

' Use strict '; // Note that each time the results are different: // [3, 5, 4, 6, 2, 1]

sample()Randomly select one or more elements:

' Use strict '; // Note that each time the results are different: // randomly selected 1: // 2 // randomly selected 3: // [6, 1, 4]

8. flatten() receive one Array , regardless of Array how many are nested inside it Array , and flatten() finally turn them into a one-dimensional array:

// [1, 2, 3, 4, 5]

9.first/last

var arr = [2, 4, 6, 8//  2//  8

10.zip/unzip

var names = [' Adam ', ' Lisa ', ' Bart ']; var = [scores,];_.zip, (names, scores); // [' Adam ', [], [' Lisa ', []], [' Bart ', ']]
var = [' Adam ', namesandscores], [' Lisa ', [], [' Bart ',]];_.unzip (namesandscores); // [ ' Adam ', ' Lisa ', ' Bart '], [ []

11.object

var names = [' Adam ', ' Lisa ', ' Bart ']; var = [scores,];_.object, (names, scores); // {adam:85, lisa:92, bart:59}

12.range

// starting from 0 less than ten: // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] // starting from 1 less than one: // [1, 2, 3, 4, 5, 6, 7, 8, 9, ten] // starting from 0 less than 30, step 5: // [0, 5, ten, +, +] // starting from 0 is greater than-10, step-1: // [0,-1,-2, -3, -4, -5,-6,-7,-8,-9]

13.bind. If you want to log() replaceconsole.log(),可以这样写:

var log = console.log; // invoke call and pass in the console object as this:log.call (console, ' Hello, world! ') )//  output Hello, world!

If bind, bind the console object directly to log() the this pointer. It can be written like this:

var log = _.bind (console.log, console); log (' Hello, world! ') ); // output Hello, world!

partial()Create a partial function for a function

Suppose we often calculate 2y, each time Math.pow(2, y) it is more troublesome to write, if you create a new function can be written directly like this pow2N(y) , the new function pow2N(y) is based on Math.pow(x, y) the created partial function, it fixed the original function of the first parameter (always 2):

var pow2n = _.partial (Math.pow, 2);p ow2n (/ / 8//  +//  1024x768

If we do not want to fix the first parameter, want to fix the second parameter, for example, want to create a partial function cube(x) , calculate x3, can be used _ as a placeholder, fixed the second parameter:

var cube = _.partial (Math.pow, _, 3); cube (/    //////   +

15.memoize can cache the results and call again without calculation:

varfactorial = _.memoize (function(n) {Console.log (' Start calculate ' + n + '!... '); vars = 1, i =N;  while(I > 1) {s= S *i; I--; } console.log (n+ '! = ' +s); returns;});//First Call:Factorial (10);//3628800//Note the console output://start calculate!...//10! = 3628800//Second Call:Factorial (10);//3628800//The console has no output but when you calculate factorial(9) it, it still recalculates.

Make every time Save:

varfactorial = _.memoize (function(n) {Console.log (' Start calculate ' + n + '!... '); if(N < 2) {        return1; }    returnn * Factorial (n-1);}); Factorial (10);//3628800//the output shows that factorial (1) ~factorial (10) are already cached://start calculate!...//start calculate 9!...//start calculate 8!...//start calculate 7!...//start calculate 6!...//start calculate 5!...//start calculate 4!...//start calculate 3!...//start calculate 2!...//start calculate 1!...Factorial (9);//362880//Console No output

JavaScript Full Learning (middle height)

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.