JavaScript self-study notes (must read) _javascript tips

Source: Internet
Author: User
Tags array sort array to string closure delete key new set pow hasownproperty

0-Determine whether the variable, parameter initialization

if (x) {}//variable is initialized or the variable is not empty or the variable is not zero

1-The Declaration function does not need to declare the return value, the parameter type, the end of the sentence does not even need '; '

function sum (i1,i2) {return i1+i2}

2-Directly declares anonymous function to use immediately

var f=function (i1,i2) {return i1+i2;}; Alert (f (1,2));//General anonymous function

alert (function (I1,I2) {return i1+i2;} (3,4)); /Direct declaration, immediate use

There is no concept of a class in 3-js, so some methods grow like a class

function Person (name,age) {this

. name=name;//dynamically adds properties, similar to the dynamic A = new Expendoobject () in C #;

This. Age=age;

This. Sayhello=function () {alert (' hello,my name is ' +name+ ' I am ' +age+ ' years old. ')}

var p1=new person (' lorry ');

P1. SayHello (); Call P1 like a class

. gender= ' male ';    Dynamically increase the ' sex ' attribute

alert (p1). Gender);

The 4-array object is an array that defines the array without the predefined length

var arr=new Array ();

arr[0]=0;

Arr[1]=1;

arr[2]=2;

for (Var i=0;i<=arr.length-1;i++) {

alert (arr[i]);

}

5-array is an array, also a dictionary, and a stack

var dict=new Array ();//As dictionary use

dict[' i ']= ' wo ';

dict[' love ']= ' ai ';

dict[' You ']= ' ni ';

Alert (dict[' I ']); Call

alert (Dict. Love) by key value///////////////(attribute of dynamic language)

 

for (var k in dict) {traversal

 alert (k)  in//js; ' I ', ' love ', ' You '--> print out is key

} for

(var k of Dict) {//JS traversal

 alert (k);  ' Wo ', ' ai ', ' ni '--> print Out is value

}

var arr = [1,2,3,4,5];//array simplified creation method

var arr = {"Lorry": "Cloud" : How to create a 20};//dictionary style

6-Traverse all elements that the current page can call

var s=null;

For (var k in document) {//object's properties are s+=k+ in the form of key

 ";";

}

alert (s);

7-Use a subscript operation like array to get the character at a specified position of the string

var s = ' Hello, world! ';

S[0]; ' H '

s[6];//'

s[12];    // '!'

S[13];    Undefined indexes that are out of range do not have an error, but all return undefined it is necessary to note that the

string is immutable and that if you assign a value to a string, there will be no errors, but there is no effect:

var s = ' Test ';

S[0] = ' X ';

alert (s);  s still for ' Test '

8-Capitalize lowercase

var s = ' Hello ';

S.touppercase ();  Return ' Hello '

    

var s = ' Hello ';

S.tolowercase ();  Return to ' Hello '

9-Search where the specified string appears

var s = ' Hello, world ';

S.indexof (' World '); Returns 7

s.indexof (' World ');//No substring found, return-1

10-Gets the substring of the specified index interval for the string

var s = ' Hello, world '

s.substring (0, 5);  Starting from index 0 to 5 (excluding 5), return ' Hello '

s.substring (7);//From index 7 start to end, return ' world '

A 11-javascript object is an unordered collection data type that consists of several key-value pairs

var xiaoming = {

 name: ' Xiaoming ',

 birth:1990,

 School: ' No.1 Middle School ', height:1.70

 ,

 weight:65,
   score:null//the last key value pair does not need to add ', '} at the end

;

Xiaoming.name;   ' Xiaoming '

Xiaoming.birth;    The 1990

Access property is done through the. operator, but this requires that the property name must be a valid variable name. If the property name contains special characters, it must be enclosed in []:


var xiaohong = {

  name: ' Little Red ',

  ' middle-school ': ' No.1 Middle School '

};

xiaohong[' Middle-school '];   ' No.1 Middle School '

xiaohong[' name '];  ' Little Red '

xiaohong.name;    ' Little Red '

xiaohong.age;//undefined

12-Detects whether the Xiaoming owns a property and uses the in operator:

' Name ' in xiaoming;//true

' Grade ' in xiaoming;//false

* * * * If in judge an attribute exists, this property is not necessarily xiaoming, It can be xiaoming inherited:


' toString ' in xiaoming;   True

* * * To determine whether a property is owned by the xiaoming itself, rather than inherited, you can use the hasOwnProperty () method:


xiaoming.hasownproperty (' name ');    True

xiaoming.hasownproperty (' toString ');//False

13-map

var m = new Map ([[' Michael ',], [' Bob ', d], [' Tracy ', 85]]];//two-dimensional array initialization method

M.get (' Michael ');

 

var m = new Map ( //Directly Initializes an empty map

m.set (' Adam ', 67);///Add the new Key-value

m.set (' Bob ');

M.has (' Adam ');    Whether there is a key ' Adam ': True

m.get (' Adam ');

m.delete (' Adam ');//delete key ' Adam '

M.get (' Adam ');    Undefined

 

var m = new Map ([[1, ' X '], [2, ' Y '], [3, ' Z ']]);

for (var n of M) {   //Traverse Map

 alert (n[1] + ' = ' + n[0]);

}

14-iterable the built-in foreach method, which receives a function that is automatically recalled each iteration.

var a = [' A ', ' B ', ' C '];

A.foreach (function (element, index, array) {

 //element: value to current element

 //Index: Point to Current index

 //array: Point to the Array object itself

 alert (element);

});

    

Set is similar to array, but set has no index, so the callback function has a maximum of two parameters:


var s = new Set ([' A ', ' B ', ' C ']);

S.foreach (function (element, set) {

 alert (element);

});

 

The callback function parameters of map are value, key, and map itself:


var m = new Map ([[1, ' X '], [2, ' Y '], [3, ' Z ']]);

M.foreach (function (value, key, map) {

 alert (value);

});

    

var a = [' A ', ' B ', ' C '];

A.foreach (function (element) {

 alert (element);

});

15-Using the array's map () method, passing in our own function, we get a new array as the result:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

Arr.map (function (x) {return

x*x;

}). ForEach (function (element) {

alert (element);//[1, 4, 9, +, BA]

});

16-use Map () to convert all numbers of array to string:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9];

Arr.map (String); [' 1 ', ' 2 ', ' 3 ', ' 4 ', ' 5 ', ' 6 ', ' 7 ', ' 8 ', ' 9 ']

17-Use the array's reduce () to do the cumulative calculation

var arr = [];

for (var x = 1; x <= + x) {

 arr.push (x);///Put 1~100 into array

}

alert (Arr.reduce (function (x,y) {return

x+ y;   Cumulative sum of all objects in the arr, returning the sum result

});

18-Make a brilliant transition with reduce (): Transform [1, 2, 5, 8, 0] into integers 12580

var arr = [1, 2, 5, 8, 0];

Alert (arr.reduce function (x,y) {return

x*10+y;

});

19-Filter out some elements of the array with filter ()

var arr = [0,1,2,3,4,5,6,7,8,9];

Alert (Arr.filter (function (x) {return

x%2===0;

}); /0,2,4,6,8//Returns true

    

to delete the empty string in an array by deleting the

var arr = [' A ', ', ', ' B ', null, undefined, ' C ', '];

Alert (Arr.filter function (s) {return

 S && s.trim ();/Note: IE9 The following version has no Trim () method

});//[' A ', ' B ', ' C ']

The 20-array sort () method defaults to converting all elements to string before sorting, so ...

[1, 2].sort (); [1, 2,]

so if you want to sort by number size, you can write this:

var arr = [];

for (var x = 1; x <= + +) {

 arr.push (x);

}

document.write (arr+ "<br/>");

document.write (Arr.sort (function (x,y) {return

x<y?true:false;

}));

 

to ignore the letter case effect, convert first to uppercase or lowercase


var arr = [' Google ', ' apple ', ' Microsoft '];

Alert (Arr.sort (function (s1, s2) {

 var x1 = s1.touppercase ();

 var x2 = s2.touppercase ();

 Return X1 < x2 false:true;

}); [' Apple ', ' Google ', ' Microsoft ']

21-Closure (Closure) Program structure

① assigns the function as the return value to the parameter, invokes the parameter to obtain the computed result var arr = [];

for (Var n=1;n<101;n++) {Arr.push (n);

 function Lazy_sum (arr) {var sum = function () {return arr.reduce (function (x,y) {return x+y;

 });

return sum;

var f = lazy_sum (arr);

    

Alert (f ());

 The function returned by ② does not execute immediately, but until the F () is invoked to perform function count () {var arr = [];

 For (Var i=1. i<=3; i++) {Arr.push (function () {return i * I;

 });

return arr; var results = count ();

Results has 3 function var f1 = results[0];

var F2 = results[1];

    

var f3 = results[2]; F1 ();

16 The returned function references the variable i, but it is not executed immediately. F2 (); 16 when 3 functions are returned, they refer to the variable i has become 4, F3 ();

 

16 so the final result is 16 * * * When you return the closure, keep in mind that the return function does not refer to any of the loop variables, or to subsequent variables that will change!

 ③ What if you must refer to the loop variable?

 The method is to create a second function, using the function's arguments to bind the current value of the variable, regardless of how the loop variable is subsequently changed, the value that is bound to the function parameter is invariant: function count () {var arr = [];

 For (Var i=1. i<=3; i++) {Arr.push (function (n) {return function () {return n*n;

 } (i));

return arr;

var results = count ();

var f1 = results[0];

var F2 = results[1]; VAr f3 = results[2]; Alert (F1 ()); 1 alert (F2 ()); 4 Alert (F3 ()); 9④ in the absence of a class mechanism, only a function of the language, with closures, you can encapsulate a private variable function creat_counter (init) {var n = init| |

 0;

 return{add:function () {n+=1;

 return n;

}} var c = Creat_counter ();

Alert (C.add ());//1 alert (C.add ());//2 alert (C.add ());//3 * * * In the returned object, a closure is implemented, which carries the local variable n, and the variable n is not accessible from the external code at all.

 

In other words, a closure is a function that carries a state, and its state can be completely hidden from the outside. 

 ⑤ uses Math.pow (x, y) to compute x^2 or x^3//math.pow (x, y)-->x^y function Make_pow (y) {return function (x) {return Math.pow (x,y); } var pow2 = Make_pow (2) var pow3 = Make_pow (3) Alert (Pow2 (3))//9 alert (POW3 (3))//27

22-arrow function (currently only Firefox support)//parameter => function body

var f = x => x*x*x

alert (f (3))//27

23-Generate Fibonacci sequence with generator

function* fib (max) {

 var t,a=0,b=1,n=1;

 while (N<=max) {

 yield A;

 T=a+b;

 A = b;

 b = t;

 n++;

 }

 return A;

}

for (Var x of fib (10)) {//Generator object document.write (x+ ') with a for ... of cycle iteration

  ;//Output 0, 1, 1, 2, 3

}

 

in sequence Generat or produces a self-increasing ID (without global variables)

function* next_id () {for

(var x = 1; x < m yield x + +);

}

var g = next_id ();

Alert (G.next (). value);//1

alert (G.next (). value);//2

alert (G.next (). value);//3

The above is a small series for everyone to bring the JavaScript self-study notes (must read) all the content, I hope that we support cloud Habitat Community ~

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.