JavaScript Advanced Programming (3) the basic concept

Source: Internet
Author: User

This chapter contains syntax, data types, flow control statements, and functions.

1. Syntax

The syntax of Ecmascrip is similar to the syntax of C and other C languages such as Java and Perl.

2. Case-sensitive

Everything in ECMAScript (variables, function names, and operators) is case-sensitive.

3. Identifiers

Refers to the name of a variable, function, property, or parameter of a function. It can also be one or more characters that are combined according to the following formatting rules:

(1) The first one must be a letter, an underscore (_), or a dollar sign ($);

(2) Other characters can be letters, underscores, dollar signs, or numbers.

(3) Extended ASCII or Unicode alphabetic characters, but this is not recommended.

Note: ECMAScript identifiers are in hump case format

You cannot use keywords, reserved words, true, false, and NULL as identifiers

4. Notes

ECMAScript includes single-line comments and block-level annotations.

A single-line comment begins with two slashes, as follows:

Single-line Comment

Block-level comments begin with a slash and an asterisk (/*), ending with an asterisk and a slash (*/). As shown below:

/** This is a multi-line * (Block-level) Comment */

Line 23rd is not required to start with an asterisk. Add to improve readability of annotations

5. Strict mode

ECMAScript introduced the concept of strict mode. is to define a different parsing and execution model for JavaScript. In strict mode, some of the indeterminate behavior in the ECMAScript will be handled and an error is thrown on some disturbed operations.

Include this compilation hint above the inside of the function, or you can specify that the function executes in strict mode:

function dosomething () {  "use strict";   function Body}

This line of code looks like a string and is not assigned to any variable, but it is actually a compilation instruction to tell the supported JavaScript engine to switch to strict mode.

In strict mode, the results of JavaScript execution can vary greatly. Browsers that support strict mode include ie10+, firefox4+, Safari, opera12+, and Chrome.

6. Statements

The statements in ECMAScript end with a semicolon, or the parser determines the end of the statement if the semicolon is omitted. Although a semicolon for a statement is not required, it is recommended that you do not omit it at any time.

var sum = a + b  //No semicolon is also a valid statement          does not recommend var diff = b;   Valid Statement        recommendations

With semicolons you can avoid many errors (such as incomplete input) and developers can safely compress ECMAScript code or, in some cases, improve the performance of the code.

You can use the C language style to combine multiple statements into a block of code, that is, the code block begins with a left curly brace ({) and ends with a closing curly brace (})

if (text) {   test = false;   alert (test);}

Although conditional control statements (if statements) require code blocks only when multiple statements are executed, it is a best practice to always use blocks of code in control statements-even if there is only one statement in the code block.

Using code blocks in a control statement can make the bias intent clearer, and it can also reduce the chance of errors when modifying the code.

7. Keywords and reserved words

ECMA-262 describes a set of keywords that can be used to represent the start or end of a control statement, or to perform a specific operation. By rule, keywords are also language-reserved and cannot be used as identifiers.

ECMA-262 also describes another set of reserved words that cannot be used as identifiers. Although reserved words do not have any specific use in this language, they may be used as keywords in the future.

Keywords and reserved words are still not used as identifiers, but can now be used as property names for objects.

8. Variables

ECMAScript variables are loosely typed, and so-called loose types can be used to hold any type of data , in other words, each variable is just a placeholder for the value to hold.

Use the var operator when defining a variable (note that var is a keyword) followed by the variable name (that is, an identifier).

VAR message;

ECMAScript also supports direct initialization of variables, so you can set the value of a variable while defining it.

var message = "HI";

In this case, a string value "HI" is saved in the variable message. Initializing a variable like this does not mark it as a string type; The initialization process is simply assigning a value to the variable. Therefore, you can modify the type of the value while modifying the variable,

var message = "Ten"; message = 100;

The variable message starts with a string value of "HI", which is then replaced by a numeric value of 100. Although it is not recommended to modify the type of values that a variable holds, this operation is valid.

Variables defined with the var operator become local variables in the scope that defines the amount of change. If you use var to define a variable in a function, the variable is destroyed after the function exits.

function test () {var message = "HI";   Local variable}test (); alert (massage);  Error!

The variable message is defined using var in the function. When a function is called, the variable is created and assigned a value. After that, the variable is destroyed immediately. So the next line of code in the example will cause an error.

You can omit the var operator to create a global variable:

function test () {  message = "HI";   Global variable}test (); alert (massage);  "HI"

This example omits the var operator so that the message becomes a global variable. So as long as the test function is called once, the variable is defined and can be accessed anywhere outside the function.

Although it is possible to define global variables by omitting the VAR operator, this is not a recommended practice. Because the global variables defined in the local scope are difficult to maintain, if the VAR operator is deliberately ignored, it can cause unnecessary confusion because the corresponding variable is not immediately defined.

You can use a single statement to define multiple variables, as long as each variable (either initialized or uninitialized) is separated by commas as follows:

var message = "Hi",    found = False, age    = 29;

This example defines and initializes 3 variables. Also because ECMAScript are loosely typed, operations that use different types of initialization variables can be done in a single statement.

9. Data type

There are 5 simple data types (also called basic data Types) in ECMAScript: Undefined, Null, Boolean, number, and string. There is also a complex data type--object,object essentially consists of a set of unordered name-value pairs.

typeof operator:

Since ECMAScript is loosely typed, there is a need for a means to detect the data type of a given variable--typeof is the operator responsible for providing this information. Using the typeof operator on a value may return one of the following strings.

"Undefined"--undefined;

"Boolean"--Boolean value;

"String"--string;

"Number"--value;

"Object"--object or null;

"Function"--functions;

Here are a few examples of using the TypeOf operator:

var message  = "some string"; alert (typeof message);        "String" Alert (typeof (Message));      "String" alert (typeof);                 "Number"
Alert (typeof null) //object special value NULL is considered an empty object reference.

These examples show that the operands of the typeof operator can be as far as possible (message) or numeric literal. Note that TypeOf is an operator and not a function, so the parentheses in the example are not required, although they can be used.

Undefined type:

The undefined type has only one value, that is, a special undefined.

Uninitialized and undeclared variable execution the typeof operator returns the undefined value.

Null type:

A null type has only one value, which is null.

Null represents an empty object pointer, which is why the "object" is returned when using the TypeOf operator to detect null values.

If a defined variable is intended to be used to hold an object in the future, it is better to initialize the variable to null instead of to another value. This way, you can know if the corresponding variable has saved a reference to an object as long as you check the null value directly.

Boolean type:

The Boolean has two literals and is true and false. is case-sensitive, otherwise it is an identifier.

To convert a value to its corresponding Boolean value, you can call the Transform function Boolean (). You can call the Boolean () function on a value of any data type and always return a Boolean value. Whether the return value is true or false depends on the data type and the actual value of the converted value.

Various data types and their corresponding conversion rules:

Number type:

Represents integers and floating-point values (double-precision numbers)

numeric literal format:

Decimal: Can be entered directly in the code;

Octal (in 8-bit cardinality): The first bit must be 0 (0), followed by the octal number sequence (0~7). If the literal value is out of range, the leading 0 is ignored and the subsequent value is parsed as a decimal value.

    16 binary (16-bit base): The first two bits are 0x followed by any hexadecimal digits (0~9 and a~f). The letter a~f is case-sensitive.

var = intnum;                           // integer var octalNum1 = 070;                    // eight-in-a-year var octalNum2 = 079;                    // invalid octal value--resolved to var octalNum3 =;                      //  var hexNum1 = 0xA;                      // 16 binary var hexNum2 = 0x1f;                     // 16 binary

In arithmetic calculations, all values in eight hexadecimal and hex are eventually converted to decimal values.

Floating point value:

Is that the number must contain a decimal point, and must have at least one digit after the decimal.

Do not test a specific floating-point value. Because floating-point numeric calculations produce rounding errors.

Range of values:

If the value of the JavaScript value range is exceeded, this value is automatically converted to a special infinity value. The value cannot continue to participate in the next calculation, infinity not be able to participate in the calculated value

You can use the Isfinite () function to determine whether a numeric value is located between the minimum and maximum values. This function returns True when it is in between.

var result = Numver.max_value + Numver.max_value;alert (isfinite (Result));       // false

Although some values are seldom present in calculations that are outside of the presentation range, they are performed on calculations of very small or large numbers. Detection of these values is possible and is required.

NaN:

That is, a non-numeric value (not a number) is a special value. Used to indicate that an operand that would have returned a number did not return a numeric value.

Two features: ① any operations involving Nan (NAN/10) will return Nan, which can cause problems in multi-step calculations.

②nan is not equal to any values, including Nan itself, and returns false.

For these two features, ECMAScript defines the isNaN () function. This function takes a parameter, which can be any type. Determine if this parameter is "not a numeric value".

IsNaN () after receiving a value, it is accepted to convert the value to a value. Some values that are not numeric are converted directly to numeric values and cannot be converted to numeric values, which causes the function to return true.

Alert (IsNaN (NaN));                                  // truealert (IsNaN (ten));                                   // False (10 is a numeric value)alert (IsNaN ("ten"));                                 // False (can be converted to a value of ten)alert (IsNaN ("Blue"));                               // true (cannot be converted to numeric)alert (IsNaN (true));                                 // False (can be converted to a value of 1)

Numeric conversions:

There are 3 functions that can convert non-numeric values to numeric values: Number (), parseint (), and parsefloat (). The first one can be used for any data type, while the other two functions are specifically used to convert a string into a numeric value.

The conversion rules for the number () function are as follows:

① if it is a Boolean value, True and false are converted to 1 and 0, respectively.

② if it is a numeric value, it is simply passed in and returned.

③ returns 0 if it is a null value.

④ if it is underfined, return Nan.

⑤ if it is a string, follow these rules:

1. If the string contains only numbers (including cases preceded by a plus or minus sign), convert them to decimal values. "123" will become 123;

2. If the string contains a valid floating-point format, "1.1", it is converted to the corresponding floating-point value;

3. If the string contains a valid hexadecimal format, such as "0xf", it is converted to a decimal integer value of the same size;

4. If the string is empty (excluding any characters), convert it to 0;

5. If the string contains characters other than the above format, convert it to Nan.

⑥ if it is an object, the valueof () method of the object is called, and the returned value is converted according to the preceding rule. If the conversion result is Nan, the object's ToString () method is called, and then the returned string value is converted again according to the previous rule.

var num1 = number ("Hello world!");                        // NaN var num2 = number ("");                                   // 0 var num3 = number ("0000011");                             //  One var num4 = number (true);                                  // 1

parseint () function conversion rules:

① ignores the spaces in front of the string until the first non-whitespace character is found;

② returns nan If the first character is not a numeric character or symbol.

③ if the string starts with "0x" and is followed by a numeric character, it is treated as a hexadecimal integer;

④ if the string starts with "0" and is followed by a numeric character, it is parsed as an octal number.

varNUM1 = parseint ("12345blue");//12345varnum2 = parseint ("");//NaNvarnum3 = parseint ("0xA");//10 (hexadecimal number)varNUM4 = parseint (22.5);// AvarNUM5 = parseint ("070");//56 (octal number)varNUM6 = parseint ("70");//70 (decimal number)varNUM7 = parseint ("0xf");//15 (hexadecimal number)

When parsing strings like octal literals using parseint (), there are differences between ECMASCRIPT3 (octal) and 5 (decimal).

To eliminate this confusion, you can provide this function with a second argument: the cardinality used when converting (that is, how many binary). Specifying cardinality affects the output of the transformation:

var num1  = parseint ("Ten", 2);                   // 2 (by binary parsing) var num2  = parseint ("Ten", 8);                   // 8 (parsing by octal) var num3   = parseint ("Ten", ten);                  // 10 (resolution by decimal) var num4   = parseint ("ten", +);                  // 16 (parsing by hexadecimal)

In order to avoid erroneous parsing, it is recommended to explicitly specify the cardinality regardless of the circumstances.

parsefloat function Conversion Rules:

① the first decimal point is valid and the second decimal point is invalid. Subsequent strings will be ignored;

② will always ignore the leading 0;

The ③ hexadecimal string is converted to 0;

④ only parses a decimal value, so it does not use the second parameter to specify the number;

⑤ If the string contains a number that can be resolved to an integer (no decimal point, or 0 after the decimal point), Parsefloar () returns an integer.

var num1 = parsefloat ("1234blue");          // 1234 (integer) var num2 = parsefloat ("0xA");               // 0 var num3 = parsefloat ("22.5");              // 22.5 var num4 = parsefloat ("22.34.5");           // 22.34 var num5 = parsefloat ("0908.5");            // 908.5 var num6 = parsefloat ("3.125e7");           // 31250000

String type:

Used to represent a sequence of characters consisting of 0 or more 16-bit Unicode characters, that is, a string. The string can be represented by double quotation marks (") or single quotation marks (').

The string in double quotation marks is exactly the same as the string in single quotation marks, but the double quotation mark must end with double quotation marks, and so is the single quotation mark.

Character literal:

The string data type contains some special character literals, also called escape sequences. Used to represent nonprinting characters, or characters that have other uses.

These character literals can appear anywhere in the string, and will also be parsed as a character.

String Features:

Once the strings are created, their values cannot be changed. To change the string saved by a variable, first destroy the original string, and then populate the variable with another string containing the new value.

Convert to String:

ToString () Method: Returns the string representation of the corresponding value.

Numeric, Boolean, object, and string values have the ToString () method. However, the null and undefined values do not have this method.

ToString () can output string values in binary, octal, hexadecimal, and even any other valid binary format.

String () Transformation function: This function allows you to convert any type of value to a string;

If the value is the ToString () method, the method (with no arguments) is called and the corresponding result is returned;

Returns "NULL" if the value is null;

If the value is nudefined, then "undefined" is returned.

Object type:

An object is actually a set of data and functions. An object can be created by executing the new operator followed by the name of the object type to be created.

Any properties and methods that the object type has also exist in more specific objects.

Detailed explanations in the later chapters.

JavaScript Advanced Programming (3) the basic concept

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.