JS Basic Notes

Source: Internet
Author: User
Tags hasownproperty

One, JS contains 6 types of data:

Primitive type (that is, base type): Number, Boolean, null, Undefined, string, and Object type objects (containing function, array, date, and so on);

The difference between = = and = = =:

= = attempts to convert data types and then compares them:

null==undefined equal;

Number==string will be converted to number such as 1== ' 1.0 '//true

boolean==? (no matter what?) What) will turn into number such as 1==true//true

Object==number|string (number or string) will attempt to convert to the base type such as new string (' hi ') = = ' Hi '//true the other is False

= = = The data types must be the same on both sides of the equals sign, except that the Nan,new object is unequal, Nan≠nan,nan and any data are unequal;

Third, the packaging object:

var str= ' string ';//Base Object string

var strobj=new string (' string ');//Wrapper Object object type can have properties, methods;

var str= ' string ';

Alert (str.length)//6

str.t=10;

Alert (STR.T)//undefined

When you try to access the base type as an object, JS converts the base type to a temporary object, and when the access is completed, the temporary object is destroyed, so str.t is undefined;

Iv. Type detection:

1, typeof: Judge the basic type and function detection, encountered null return object failure;

typeof//number

typeof true//boolean

typeof function//function

typeof (undefined)//undefined

typeof New Object ()//object

typeof [//object]

typeof NaN//number

typeof Null//object

2. instanceof: Judging object type (based on prototype chain), suitable for custom object and native object;

OBJ instanceof object: Determines whether there is a prototype on the right-hand side of the prototype chain of the left-hand object;

[1,2]instanceof Array===true

New Object () instanceof Array===false

Note: Object type detection between different windows or IFrame cannot be used with instanceof, otherwise the return value is all false;

3. Object.prototype.toString: Judging Object type

Object.prototype.toString.apply ([]); = = = ' [Object Array] '

Object.prototype.toString.apply (function () {}); = = = ' [Object function] '

Object.prototype.toString.apply (null); = = = ' [object null] '

Note: Object.prototype.toString.apply (null) in IE6, 7, 8; = = = ' [Object Object] '

Object.prototype.toString.apply (undefined); = = = ' [Object undefined] '

4, constructor

5. Duck Type

Five, Operator:

1. Conditional operators:

C?A:B;

var val=true?1:2//If Val=true is established, then val=1, otherwise val=2;

2. Comma operator:

b;

var val= (All-in-one);//start from left to right, and end with the rightmost value, val=3;

3, delete operator: Delete the object's properties;

var obj={x:1};

obj.x;

Delete obj.x;//deletes the x attribute of obj;

obj.x;//undefined

Note: When Configurable:false, delete obj.x fails; configurable:true, delete obj.x is valid;

var obj={};

Object.defineproperty (obj, ' x ', {

Configurable:false,

Value:1

})

Delete obj.x;//Delete obj's X property is invalid, return false;

Obj.x;//1

4, in operator: judgment is not in an object;

Window.x=1;

' X ' in Window;//true

5, instanceof and typeof operators:

{}instanceof Object; True

typeof 100=== ' number '; True

6. New operator:

function Foo () {};//creates a constructor

Foo.prototype.x=1;

var obj=new Foo ();

obj.x;

Obj.hasownproperty (' x '); False to determine if x is an attribute on the object obj

Obj._proto_.hasownproperty (' x '); True to determine if X is a property on the prototype chain prototype

7. This operator:

This This is window in the global scope (browser)

var obj={

Func:function () {

return this;

}

}

Obj.func ();//obj this is obj

8. void Operator:

void 0//undefined

void (0)//undefined

Note: operator precedence:

Operator Describe
. [] () field access, array subscripts, function calls, and expression grouping
++ -- - ~ ! Delete new typeof void Unary operators, return data types, object creation, undefined values
* / % Multiplication, division, modulo
+ - + addition, subtraction, string connection
<< >> >>> Shift
< <= > >= instanceof Less than, equal to, greater than, greater than or equal to, instanceof
== != === !== Equal, not equal, strictly equal, not strictly equal
& Bitwise-AND
^ Bitwise XOR OR
| Bitwise OR
&& Logic and
|| Logical OR
?: Conditions
= op= Assignment, Operation assignment
, Multi-value evaluation

VI. Try-catch Statement: Exception capture mechanism

try{

Throw ' test ';

}catch (ex) {

Console.log (ex); Test

}finally{

Console.log (' finally ');

}

Execution process: The code in the try block is executed first, if an exception is thrown, the catch is caught and the console is executed, and if no exception occurs, the code in the catch is ignored, regardless of whether there is an exception, and finally a finally clause is executed ; Note: A catch or finally clause must be followed by a try;

try{

}finally{

Console.log (' finally '); No matter if there is an exception, finally the final clause is executed

}

try{

try{

throw new Error (' oops ');

}finally{

Console.log (' finally ');

}

}catch (ex) {

Console.error (' outer ', ex.message); The result of the execution is finally outer oops, because there is no catch in the internal try, it is necessary to execute the catch that is closest to him, but there is finally in the internal try, so the finally is executed first, output Finally, then the catch , output outer, and finally execute internal try, output oops;

}

try{

try{

throw new Error (' oops ');

}catch (ex) {

Console.error (' inner ', ex.message);

}finally{

Console.log (' finally ');

}

}catch (ex) {

Console.error (' outer ', ex.message); The execution result is inner oops finally, because after the internal try throws the oops exception, the internal catch block is executed first, the output inner oops, and then finally, the output finally, because the exception has been processed internally, The outer try does not need to execute the exception again;

}

try{

try{

throw new Error (' oops ');

}catch (ex) {

Console.error (' inner ', ex.message);

Throw ex;

}finally{

Console.log (' finally ');

}

}catch (ex) {

Console.error (' outer ', ex.message);//The execution result is inner oops finally outer oops, because after an internal try throws a oops exception, the internal catch is executed, the output inner, However, the internal catch throws an exception, the output oops, so it goes to the external catch, but to execute the external catch before executing the internal finally, the output finally, and then output outer, and then output oops;

}

Seven, object: (JS out of the basic type is only the object) contains functions, arrays, regular, date and so on;

1, the object contains a series of attributes, and the properties are unordered, each property has a string of key and value, the attributes are separated by commas;

2. Create objects:

Literal way:

var a={x:1,y:2,z:{a:2,b:4}};

New or prototype chain:

functionfoo () {}foo.prototype.z= 3;varobj =Newfoo (); Obj.y= 2; obj.x= 1; obj.x;//1obj.y;//2obj.z;//3typeofobj.tostring;//' function '' Z 'inchObj//trueObj.hasownproperty (' Z ');//false to determine if the prototype attribute is included

Object.create Method:

var obj = object.create ({x:1//  1typeof//  "function" obj.hasownproperty (' x '); // false var obj = object.create (null//  undefined

3. Object Properties Delete:

Note the following properties cannot be deleted:

Delete Object.prototype; False

The global variables defined by var or local variables, function life (either global or local) cannot be deleted because these are not properties of the object, but the implicit function can be deleted, as follows:

oh=1;

Window.oh;//1

Delete Oh; True

4. Attribute detection:

Cat.hasownproperty (' legs '); True to determine if cat contains legs attributes;

Cat.propertyisenumerable (' legs '); True to detect whether a cat's properties can be enumerated

Object.defineproperty (cat, ' price ', {enumerable:false,value:1000}); Disable the cat attribute from being enumerated DefineProperty: Create property

Cat.propertyisenumerable (' price '); False

5, get or Set method read and write properties:

var man = {    ' bosn ',    ' @Bosn ',    get-age ()        {returnNew  Date (). getFullYear ()-1988;    },    set Age (val) {        console.log (' age can\ ' t is set to ' +  val);     //  - // Age can ' t is set to // still

6. Attribute Tags:

true}, ' Pro '); the Getownpropertydescriptor () method returns the label of the property
// Object {value:true, writable:true: Can be modified, enumerable:true: Can be traversed, configurable:true: Whether other property tags can be temporarily modified}
true // undefined

7. Serialization of objects:

Convert JSON data to object: Json.stringify ()

var obj = {x:1, y:true, z: [1, 2, 3], nullval:null};  Json.stringify (obj); "{" X ": 1," Y ": true," Z ": [Nullval]," "": null} "

obj = {val:undefined, A:nan, b:infinity, C:new Date ()};  Json.stringify (obj); "{" A ": null," B ": null," C ":" 2015-01-20T14:15:43.910Z "}"

Convert an object to Json:JSON.parse ()

obj = Json.parse (' {"X": 1} ');  obj.x; 1

Eight, array: the length of the array is 2 the maximum of 23 square minus 1, that is, 2^23-1, more than will error;

1. Create an array:

New Array Mode:

var arr = new Array ();

var arrwithlength = new Array (100); Undefined * 100

var arrlikesliteral = new Array (true, False, NULL, 1, 2, "HI"); Equivalent to [true, false, NULL, 1, 2, "HI"];

"" Way:

var BAT = [' Alibaba ', ' Tencent ', ' Baidu '];

var students = [{name: ' Bosn ', age:27}, {name: ' Nunnly ', age:3}];

var arr = [' nunnly ', ' is ', ' big ', ' Keng ', ' B ', 123, true, NULL];

var Arrinarr = [[1, 2], [3, 4, 5]];

var commasArr1 = [1, 2]; 1, Undefined, 2

var commasArr2 = [,,]; Undefined * 2

2, the array reads and writes: The array starts from the index=0, the first bit index=0;

Delete A[0];console.log (a[0]); Undefined

3. Array element Processing:

Arr.pop (): Removes the element at the tail of the array;

Arr.push (3): Adds an element from the tail of the array;

Arr.shift (): Adds an element from the head of the array;

Arr.unshift (0): Delete the elements of the array header;

var arr = [];

Arr[0] = 1;

ARR[1] = 2;

Arr.push (3);

Arr [1, 2, 3]

Arr[arr.length] = 4; Equal to Arr.push (4);

Arr [1, 2, 3, 4]

Arr.unshift (0);

Arr [0, 1, 2, 3, 4];

Delete Arr[2];

Arr [0, 1, Undefined, 3, 4]

Arr.length; 5

2 in Arr; False

Arr.length-= 1;

Arr [0, 1, Undefined, 3, 4], 4 is removed

Arr.pop (); 3 returned by pop

Arr [0, 1, undefined], 3 is removed

Arr.shift (); 0 returned by shift

Arr [1, undefined]

4. Small Note:

①.+ operator Note:

a=+b;//here +b means converting B to number numeric type

a+=b;//here, a+=b means a=a+b, it's a digital operation.

②.isnan: It can be understood that first nan:not a number is not a digit, and IsNaN is understood to be: is isn't a number not a digit, so in the If judgment, IsNaN is true, indicates whether a number, that is, the number type, When judged to be false, the representation is not a number, that is, a numeric type, so a Boolean value that isNaN is judged to be a numeric type should be false; (note that Nan is a numeric type)

JS Basic Notes

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.