Basic JavaScript Learning

Source: Internet
Author: User
Tags arithmetic operators throw exception alphanumeric characters

First, JavaScript overview The history of JavaScript
    • 1992 Nombas developed the embedded scripting language for C-minus-minus (c--) (originally bundled in Cenvi software). Rename it scriptease. (The language that the client executes)

    • Netscape (Netscape) received Nombas's philosophy, (Brendan Eich) developed a set of Netscape scripting languages in its Navigator livescript 2.0 product. Sun and Netscape are done together. And then the name is JavaScript.

    • Microsoft then emulated a JavaScript clone called JScript in its IE3.0 product.

    • To unify the three, the ECMA (European Computer Manufacturing Association) defines the ECMA-262 specification. The International Organization for Standardization (ISO/IEC) also adopted ECMAScript as the standard (iso/iec-16262). Since then, Web browsers have struggled (albeit with varying degrees of success and failure) to ECMAScript as the basis for JAVASCRIPT implementations. ECMAScript is the norm.

ECMAScript

Although ECMAScript is an important standard, it is not the only part of JavaScript, and certainly not the only one that is standardized. In fact, a complete JavaScript implementation is made up of the following 3 different parts:

    • Core (ECMAScript)
    • Document Object Model (DOM) Documents object models (consolidated js,css,html)
    • Browser object models (BOM) Broswer object Model (integrated JS and browser)
    • The vast majority of Javascript in development is object-based. It is also object-oriented.

To put it simply, ECMAScript describes the following:

    • Grammar
    • Type
    • Statement
    • Key words
    • Reserved words
    • Operator
    • Object (encapsulates inherited polymorphism) object-based language. Use an object.
Two JavaScript based 2.1 js Introduction method
1 Direct Write    <script>        alert (' Hello Yuan ')    </script>2 import file    <script src= "Hello.js" ></ Script>
2.2 JS variables, constants and identifiers 2.2.1 JS variables
X=5y=6z=x+y

In algebra, we use letters (such as x) to hold values (such as 5). By the above expression Z=x+y, we can calculate the value of Z as 11. In JavaScript, these letters are called variables.

So how to define the use of variables in JS?

1. Do not declare variable types when declaring variables. All use the var keyword;

var a;a=3;

2, a row can declare multiple variables. And can be of different types

var name= "Yuan", age=20, job= "lecturer";

3 . You can declare variables without var. if you don't use Var then it's a global variable

4, the name of the variable, the first character can only be letters, underscores, $ dollar symbol three select one, the remaining characters can be underscores, dollar signs or any alphanumeric characters and case-sensitive, x and X are two variables

5 variables should also adhere to one of the following well-known naming conventions:

The first letter of the Camel notation is lowercase, and the next letters begin with uppercase characters. For example: var mytestvalue = 0, Mysecondvalue = "HI"; The first letter of the Pascal notation is capitalized, and the next letters begin with uppercase characters. For example: Var mytestvalue = 0, Mysecondvalue = "HI"; Hungarian type notation appends a lowercase letter (or a lowercase sequence) to a variable named after the Pascal notation, indicating the type of the variable. For example, I represents an integer, S represents a string, as shown below "Var imytestvalue = 0, Smysecondvalue =" HI ";
Note:
function Func1 () {                var a = 123;        b=456    }    func1 ();    alert (a);//    alert (b);//Not recommended
2.2 Basic Specifications

1 the end of each line can be without a semicolon. No semicolon will end with a newline character as each line

A=1;b=2;a=1 b=2;------error a=1b=2//recommended a=1;b=2; {a=1; b=2;    Recommended Add tab    a=1;    b=2;}

2 Comments Support multiline comments and single-line comments./* */ /

3 using {} to encapsulate a block of code

2.3 Constants and identifiers

Constants : data values that appear directly in the program

identifiers :

    1. Consists of letters, numbers, underscores (_), Dollar signs ($) that do not begin with a number
    2. a name commonly used to denote functions, variables, etc.
    3. For example: _ABC, $ABC, abc,abc123 is an identifier, and 1ABC is not
    4. Words that represent a particular meaning in the JavaScript language are called reserved words and do not allow programs to be redefined as identifiers

2.4 Data types

               /*  Number-----Numeric        Boolean    -----boolean string     -----  string        undefined  - ----  undefined        null       -----   NULL         */
2.3.1 Numeric type (number)

    • Integer and floating-point values are not distinguished;
    • All numbers are stored in 64-bit floating-point format, equivalent to the double format in the Java and C languages
    • The maximum value that can be represented is ±1.7976931348623157 x 10308
    • The minimum value that can be expressed is ±5 x 10-324

Integer:
10 integers in JavaScript consist of sequences of numbers
What is the exact range of the expression?-9007199254740992 (-253) to 9007199254740992 (253)
Integer out of range, accuracy will be affected
Floating point number:
Using decimal points to record data
Example: 3.4,5.6
Use Index to record data
Example: 4.3e23 = 4.3 x 1023

16 binary and 8 decimal expressions:
16 binary data before adding 0x, octal front plus 0;16 is composed of 16 characters, such as 0-9,a-f, 8 binary number consists of 0-7 8 digits

16 binary and 8 binary vs. 2 binary conversions:

2 binary: 1111 0011 1101 0100   <-----> 16:0xf3d4 <-----> 10 binary: 624202 binary: 1 111 001 111 010 <-----> 8 in System: 0171724
2.3.2 The String type (string)
Introduction is a sequence of string constants consisting of Unicode characters, numbers, and punctuation marks the end of a single quotation mark or double quotation mark in a JavaScript that does not have a character type common special characters in the string expression string in a part special characters must be added to the right dash common escape character \ n: line break  \ ' : Single quotation mark   \ ": double quotation mark \  \: Right Dash

Use of the string data type

    • How to use special characters and their effects
    • How Unicode is inserted
<script>        var str= "\u4f60\u597d\n Welcome to \" JavaScript world \ "";        Alert (str);</script>
2.3.3 Boolean Type (Boolean)

The Boolean type has only two values: True and False, also representing 1 and 0, in the actual operation True=1,false=0
Boolean values can also be considered on/off, yes/no, 1/0 correspondence True/false
The Boolean value is primarily used for JavaScript control statements, such as:

if (x==1) {      y=y+1;} else{      y=y-1;      }
2.3.4 Null & undefined type

Undefined type

The Undefined type has only one value, which is Undefined. When the declared variable is not initialized, the default value of the variable is undefined.

When the function has no definite return value, the returned value is also "undefined";

Null type

Another type with only one value is null, and it has only one private value, NULL, which is its literal. The value undefined is actually derived from the value null, so ECMAScript defines them as equal.

Although the two values are equal, they have different meanings. Undefined is a value that is assigned to a variable when it is declared but not initialized, and null is used to represent an object that does not already exist (this is briefly described when discussing the typeof operator). If the function or method is to return an object, the object returned is usually null when it is not found.

var person=new person ()

var person=null

Data type Conversions
JavaScript is a loosely typed program language variable that does not need to specify a data type variable at the time of declaration it is determined that the data type expression contains different types of data when it is assigned, and the class conversions are enforced during the calculation. Number + string: Number converted to string number + Boolean: True to convert 1,false to 0 string + Boolean: Boolean converts to string true or False

Coercion type conversion function

function parseint:   cast to integers   such as parseint ("6.12") =6  , parseint ("12a") =12, parseint ("A12") =nan  ;p arseint (" 1a2 ") =1 function parsefloat: Cast to floating-point number  parsefloat (" 6.12 ") =6.12 function eval:       cast the string to an expression and return the result eval (" + ") =2; eval (" 1< 2 ") =true
type query function (typeof )

ECMAScript provides the typeof operator to determine whether a value is within a certain type of range. You can use this operator to determine whether a value represents an original type: if it is the original type, you can also determine which primitive type it represents.

2.4 operatorECMAScript arithmetic operators
Add (+), subtract (-), multiply (*), divide (/), remainder (%)  Add, subtract, multiply, divide, remainder, and mathematical methods  for example: 9/2=4.5,4*5=20,9%2=1-In addition to representing a minus sign can also represent a negative sign  such as: x=-y+ In addition to the connection that can be used to represent an addition operation for a string,  for example: "abc" + "def" = "abcdef"

Increment (+ +), decrement (--)

If x=2, then the value of the X + + expression after the execution of the 3,x--expression is 1i++ equivalent to i=i+1,i--equivalent to the i=i-1 increment and decrement operators can be placed before the variable can also be placed after the variable:-    i var i=1;console.log (i + +); Console.log (++i); Console.log (i--); Console.log (i.);

Unary Plus subtraction:

var a=1;    var b=1;    a=-a;  A=-1    var c= "ten";    Alert (typeof (c));    C=+c;    Type conversion    alert (typeof (c));//    -------------------    var d= "Yuan";    D=+d;    alert (d);//nan: A special value of type number that gets a NaN data alert (typeof (D)) when it encounters an invalid to convert the string to a digit    ;//number    //nan Features:        var N=nan;        alert (n>3);    alert (n<3);    alert (n==3);    alert (N==nan);        alert (N!=nan); All operations that//nan participate in are false, except! =
ECMAScript logical operators
Equal to (= =)  , not equal to (! =), greater than (>), less than (<)? greater than or equal to (>=), less than or equal (<=) with (&&), or (| |), non-(!) 1 && 1 = 1  1 | | 1 = one && 0 = 0  1 | | 0 = Ten && 0 = 0  0 | | 0 = 0!0=1!1=0
Logical AND Operator (&&)

The operands of a logical AND operation can be of any type, not just a Boolean value.

If an operand is not the original Boolean value, the logical AND operation does not necessarily return a Boolean value:

    • Returns null if one of the operands is null.
    • If an operand is Nan, a nan is returned.
    • If one of the operands is undefined, return to undefined.
logical OR operator (| |)

Similar to the logical AND operator, a logical OR operation does not necessarily return a Boolean value if an operand is not a Boolean value

ECMAScript assignment operator
Assignment = in JavaScript = for assignment, two equals = = to determine equality For example, x=1 indicates that x is assigned a value of 1if (x==1) {...} The program represents when x is equal to 1 if (x== "on") {...} The program represents a simplified expression that is formed with other operators when X is equal to "on" such as i+=1 equivalent to i=i+1,x&=y equivalent to X=x&y

Instance:

= = "2"        = = = "2"! =        "4"            !== "4"        var a = 2; var b = 4;var c = a<b |--b>--a;var c = A<B | |--b>-- A;  var C = a<b &&--b>--a;var c = a<b &--b>--a;
ECMAScript equal-sex operators

The rules for performing type conversions are as follows:

    • If one of the operands is a Boolean value, convert it to a numeric value before checking for equality. False converts to 0,true to 1.
    • If one operand is a string and the other is a number, try converting the string to a number before checking for equality.
    • If one operand is an object and the other is a string, try to convert the object to a string before checking for equality.
    • If one operand is an object and the other is a number, try converting the object to a number before checking for equality.

The operator also adheres to the following rules when comparing:

    • The value null and undefined are equal.
    • When checking for equality, null and undefined cannot be converted to other values.
    • If an operand is NaN, the equal sign returns false, and the non-equal sign returns TRUE.
    • If the two operands are objects, then their reference values are compared. If two operands point to the same object, then the equals sign returns TRUE, otherwise two operands are not equal.

ECMAScript relational operators (important)
var bresult = "Blue" < "alpha"; alert (bresult); Output true

In the example above, the string "Blue" is less than "alpha" because the character code of the letter B is 66, and the character code for the letter A is 97.

Comparing numbers and strings

Another tricky situation occurs when comparing numbers in the form of two strings, such as:

var = "Bresult" < "3"; alert (bresult); Output "true"

The above code compares the strings "25" and "3". Two operands are all strings, so the comparison is their character code ("2" character code is 50, "3" character code is 51).

However, if one of the operands is a number, the result is interesting:

var = "Bresult" < 3;alert (bresult); Output "false"

Here, the string "25" will be converted to the number 25, and then compared with the number 3, the results are expected.

Summarize:

Comparison operator on either side if one is a numeric type and one is a different type, its type is converted to a numeric type. The comparison operator on both sides if all are string types, compare the highest bit ASC code, and if the highest bit is equal, continue to take the second bit comparison.
Boolean operator (important)
var temp=new Object ();//false; [];0; Null Undefined;object (New object ();)    if (temp) {        console.log ("Yuan")    }else {        console.log ("Alex")    }

2.5 Process ControlIf control statement
If-else basic format if (expression) {statement 1; ...} else{statement 2; ...} Function description if the value of the expression is true Then statement 1 is executed, otherwise the statement 2 is executed

var x= (new Date ()). GetDay ();//Get today's week value, 0 for Sunday var y;if ((x==6) | | (x==0)) {y= "Weekend";} Else{y= "Weekday";} alert (y);//equivalent to y= "weekday"; if ((x==6) | | (x==0)) {y= "Weekend";}

If can be used alone

If statement nested format if (expression 1) {    statement 1;} else if (expression 2) {    statement 2;} else if (expression 3) {    statement 3;} else{    statement 4;}

if (x==1) {    y= "Monday";} else if (x==2) {    y= "Tuesday"; ...} else if (x==6) {    y= "Saturday";} else if (x==0) {    y= "Sunday";} else{    y= "undefined";
Switch Select control statement
Switch basic format switch (expression) {case    value 1: statement 1;break;    Case value 2: statement 2;break;    Case Value 3: statement 3;break;    Default: statement 4;}

Switch (x) {case 1:y= "Monday";    Break;case 2:y= "Tuesday";    Break;case 3:y= "Wednesday";    Break;case 4:y= "Thursday";    Break;case 5:y= "Friday";    Break;case 6:y= "Saturday";    Break;case 7:y= "Sunday";    break;default:y= "undefined";}

Switch more concise and clear than the else if structure, making the program more readable and more efficient.

The first thing to look at is a question,ifStatements can be used in a wide range of applications, as long as they are Boolean expressionsifJudge;SwitchYou can only perform numeric comparisons on basic types. The comparability of the two is limited to the comparison of two basic types. When it comes to numerical comparisons of basic types, of course there are two numbers. And then the point is--ifstatement each sentence is independent, see the following statement:if(A = =1) ...Else if(A = =2) ... So that a is read into the register two times,1And2are read into the register one time, respectively. So did you find that actually a read two times is a bit redundant, you only need to read the register one time before all the comparison is complete, the rest is the extra cost. ButifThe statement must each time the two numbers inside out of memory to read the register, it does not know that you actually compare the same a. SoSwitch  CaseIt's out, change the top toSwitch  Caseversion:Switch(a) { Case 0:                 Break;  Case 1:} Summary:1. switch is used to route a multi-branch based on an integer value, and the compiler can optimize the Multipath branch2.Switch-The case evaluates the expression only once and then compares the value of the expression to the value of each case, and then selects the statement block that executes which case3.if..Elsethe range of judging conditions is wide, each statement is basically independent, each time the judgment is conditional loading. So use the switch ratio if in the multi-channel branch.Else if.. Else structure is highly efficient.
Why is switch high efficiency? For loop control statements
For loop basic format for (initialize; condition; increment) {    statement 1;    ...} The function description realizes the condition loop, when the condition is established, executes the statement 1, otherwise jumps out the loop body

for (Var i=1;i<=7;i++) {    document.write ("

Attention:

Doms=document.getelementsbytagname ("P");    for (var i in doms) {       console.log (i);//0 1 2 Length item Nameditem       //console.log (doms[i])    }//loop is the th one you get The DOM element set, for in is used to loop through all the properties of an object, and the DOM element set contains the attributes you output above. If you just loop the DOM object, you can use a For loop: for    (var i=0;i<doms.length;i++) {        console.log (i);//0 1 2        //console.log (Doms[i])    }

Conclusion: For I in is not recommended.

While loop control statement
While loop basic format while (condition) {statement 1; ...} Function description run function and for similar, when the condition is formed loop execution statement curly braces {} Inside the statement, otherwise jump out of the loop

var i=1;while (i<=7) {    document.write ("

<script language= "JavaScript" >/* SayHello is a defined function name that must precede the functions and spaces */function SayHello () {    var hellostr;    var myname=prompt ("May I have your surname?") "," the Court ");     hellostr= "Hello," Mr. +myname+ ', Welcome to the Discovery Tour! ';    alert (HELLOSTR);     document.write (HELLOSTR);} Here is a call to the previously defined function SayHello ();</script>

Exercise: Calculate the and of 1-100 with a for loop and a while loop, respectively?

Exception Handling
try {    //This piece of code runs from top to bottom, where any one of the statements throws an exception the code block ends running}catch (e) {    ///If an exception is thrown in a try code block, the code in the catch code block is executed.    //e is a local variable that is used to point to an Error object or other thrown object}finally {//Whether or not the code in the     try is thrown (even if there is a return statement in the try code block), the finally code block is always executed. }

Note: Throw exception throw error (' xxxx ')

 

Basic JavaScript Learning

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.