Learning Notes (ii) JavaScript basic concepts (syntax, data types, control statements, functions)

Source: Internet
Author: User

I. Grammar

Everything in 1.javascirpt (variables, function names, and operators) is strictly case-sensitive.

2.javascript (identifier)

An identifier is a variable, a function, the name of a property, or an argument to a function.

Naming rules: The first character must be a letter, underscore, dollar sign, and other characters can be letters, underscores, dollar signs, or numbers.

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

3.The ECMAScript identifier is in hump case format, that is, the first letter is lowercase, and the first letter of each of the remaining words is capitalized. (but no one is obligated to require this format)

4. Notes

Single-line Comment
/*
* This is a multiline comment
*/

5. Statements

It is best to end each statement with a semicolon, but you can also omit the semicolon.

You can combine multiple statements into a block of code, and the code block begins with a left curly brace ({) and ends with a right curly brace (}).

if (test)
alert (test); Effective but error-prone, preferably not used

if (test) {

alert (test);//Recommended Use
}

6. Keywords and reserved words

7. Variables

Variables are loosely typed and can be used to hold any type of data. Use the keyword var to declare the variable.

VAR message; A variable like this that has not been initialized will hold a special value undefined

obj=100; This is valid but not recommended, which is equivalent to declaring a global variable

two. ECMAScript has 5 simple data types:Undefined,null,boolean,number and string and 1 complex data types Object

1.typeof operator: unary operator, which can be either a variable or a numeric literal to detect the data type of a given variable.

Possible return values:

1). ' Undefined '---this value is undefined;

2). ' Boolean '---This value is a Boolean value;

3). ' String '---This value is a string;

4). ' Number '---this value is numeric;

5). ' Object '---This value is an object or null;

6).---This value is a function.

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

VAR message;

alert (message==undefined); True

The variable that contains the undefined value is not the same as the variable that has not been declared.

VAR message;

var age;
alert (message); Undefined
alert (age); Error generated

Executes a typeof on a variable that has not been declared, the result returns undefined, executes typeof on a variable that has not been initialized, and returns undefined

VAR message;

var age;
Alert (typeof message); Undefined
Alert (typeof age); Undefined

It is best to display the initialization variables, so that when the typeof operator returns the undefined value, we know that the variable being detected is not declared, not yet initialized, because a variable without a declaration is returned directly with the typeof operator undefined

3.null type

A null type has only one value, which is special null. A null value represents an empty object pointer, and the typeof operator detects that the null value returns "Object".

A comparison between null and the equality operator (= =) between undefined always returns TRUE.

4.Boolean type

Only two literals: true and false, these two values are not the same as numeric values, and true does not necessarily mean that 1,false is not necessarily equal to 0, and that the two literals are case-sensitive.

To convert a value to its corresponding Boolean value, you can call the Transform function Boolean ().

In JavaScript, any data type called a transform function, Boolean (), always returns a Boolean value, with various data types and conversion rules as follows:

5.Number type

Include integers and floating-point numbers

1). Integers include decimal, octal literals, and hexadecimal literal values.

The first digit of the octal literal must be zero and the first two digits of the hexadecimal literal must be the ox.

In arithmetic calculations, octal literals and hexadecimal literals are eventually converted to decimal values.

2). Floating point number

The so-called floating-point value, which must contain a decimal point, and must have at least one digit after it. There can be no integers before the decimal point, but it is not recommended.

Floating-point numbers can be this way: var floatnum =. 1; But this is not recommended.

Since the memory space required to save floating-point values is twice times the integer value, it is no longer a chance to convert floating-point numbers to integer values if there are no digits after the decimal point, the value can be saved as an integer value, as well, If the floating-point number itself represents an integer, such as 1.0, the value is also converted to an integer.

For maximum and minimum values, use scientific notation. The highest precision for floating-point values is 17 decimal places.

Number.MAX_VALUE the maximum value of an integer

Number.min_value the minimum value of an integer

If you calculate a value that exceeds the range of JavaScript values, the value is automatically converted to a special infinity, and if a positive or negative infinity value is returned, it will not continue to participate in the next calculation

To determine whether a value is poor, you can use the Isfinite () function if the argument is between the maximum and the minimum number to return true.

Access to number.negative_infinity and number.positive_infinity can get the value of positive and negative infinity, so the two properties are actually saved-infinity and infinity respectively.

3). NaN

Nan Features: 1 any operation involving Nan will return Nan,2nan not equal to any value, including the Nan itself.

IsNaN () This function takes a parameter that can be of any type, and this function will help us determine if the parameter is "not a number", not a numeric value that returns TRUE.

IsNaN () This function takes a parameter and tries to convert it to a numeric value. Any value that cannot be converted to a number will cause the function to return true.

Alter (IsNaN (NaN));//true

Alter (IsNaN);//true

Alter (IsNaN ("ten"));//true

Alter (IsNaN ("Red"));//false

Alter (IsNaN (TRUE));//true

4). Numeric conversions

There are three functions that can convert non-numeric values to numeric values: Number (), parseint (), parsefloat ()

The transformation type number () can be used for any data type, parseint (), and parsefloat () is specifically used to convert a string into a numeric value.

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

(1) If it is a Boolean value, True and false are converted to 1 and 0, respectively
(2) If it is a numeric value, simply pass in and return
(3) If it is a null value, return 0
(4) If it is undefined, return Nan
(5) If it is a string, follow these rules:
If the string contains only numbers, it is converted to a decimal value, the level "1" becomes 1, "123" becomes 123, and "011" becomes 11 (the preceding 0 is ignored)
If the string contains only a valid floating-point format, such as "1.1", it is converted to the corresponding floating-point value (also ignoring the leading 0)
If the string contains only valid hexadecimal formats, such as "0xf", it is converted to a decimal integer value of the same size
If the string is empty (contains no characters), it is converted to 0
If the string contains characters other than the above format, it is converted to Nan
(6) 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 result of the conversion is Nan, then the ToString () of the calling object converts the various data types to values that are indeed somewhat complex. Here are a few specific examples:
var num1 = number ("Hello world!"); NaN
var num2 = number (""); 0
var num3 = number ("000011"); 11
var num4 = number ("true"); 1

parseint ()

When the parseint () function converts a string, it ignores the space in front of the string until it finds the first non-whitespace character.

If the first character is not a numeric character or minus sign, parseint () returns Nan, that is, converting an empty string with parseint () returns Nan (number () returns 0 for an empty string).

If the first character is a numeric character, parseint () continues to parse the second character until all subsequent characters have been parsed or a non-numeric character is encountered.

For example, "123blue" is converted to 1234 because "blue" is completely ignored. Similarly, "22.5" is converted to 22 because the decimal point is not a valid numeric character.

If the first character in a string is a numeric character, parseint () can also recognize various integer formats (that is, decimal, octal, hexadecimal). That is, if the string starts with "0x" and is followed by a numeric character, it is treated as a hexadecimal integer, and if the string starts with "0" followed by a numeric character, it is parsed as an octal number or decimal.

To better understand the conversion rules for the parseint () function, here are some examples:

var num1 = parseint ("1234blue"); 1234
var num2 = parseint (""); NaN
var num3 = parseint ("0xA")//10 (hex)
var num4 = parseint ("22.5"); 22
var num5 = parseint ("070"); 56 or 70 (octal)
var num6 = parseint ("70"); (70) Decimal
var num7 = parseint ("0xF")//15 (hex)

parseint () resolves "070", causing the confusion above, and ECMAScript also provides the second parameter for this function: the cardinality used when converting (that is, how many binary).

Specifying the cardinality affects the output of the transformation.

var num1 = parseint ("AF", 16); 175
var num2 = parseint ("AF"); NaN
The first conversion in this example succeeds, and the second fails. The difference is that the first transformation passes in the cardinality, explicitly telling parseint () to parse a hexadecimal-formatted string, and the second transformation finds that the first character is not a numeric character and therefore terminates automatically.

var num1 = parseint ("10", 2); 2
var num2 = parseint ("10", 8); 8
var num3 = parseint ("10", 10); 10
var num4 = parseint ("10", 16); 16

Parsefloat ()

Parsefloat () also parses each character from the first character (position 0), resolves to the end of the string, or resolves to an invalid floating-point numeric character. That is, the first decimal point in the string is valid, and the second decimal point is invalid, so the string following it is ignored. For example, "22.34.5" will be converted to 22.34.

Except for the first decimal point, the second difference between parsefloat () and parseint () is that it always ignores leading zeros. Because Parsefloat () parses only the decimal value, it does not specify the usage of the cardinality with the second argument. Strings in hexadecimal format are always converted to 0. Finally, note that if a string contains a number that can be resolved to an integer (no decimal point, or 0 after the decimal point), parsefloat () returns an integer. Here are a few typical examples of using parsefloat () to convert values:

var num1 = parsefloat ("1234blue"); 1234
var num1 = parsefloat ("0xA"); 0
var num1 = parsefloat ("22.5"); 22.5
var num1 = parsefloat ("22.34.5"); 22.34
var num1 = parsefloat ("0908.5"); 908.5
var num1 = parsefloat ("3.125e7"); 31250000

6.String type

The string represented by double quotation marks is exactly the same as the string in single quotation marks, and any string length can be obtained by its length property.

Character string: Once a string is created, their value cannot be changed. To change the string saved by a variable, first destroy the original string, and then populate the variable with a string containing the new value.

ToString ()-converts to a string

toString () method of numeric value: Converts a numeric value to a string, returning the string representation of the number. You can pass in a cardinality that returns the string representation of a numeric value in decimal, octal, and hexadecimal format.

String toString () method: Returns a copy of the string.

Convert to String Method tostring (), numeric, Boolean, object, and string are some methods, but null and undefined values do not have this method

When you do not know that a value is null or a undefined value, you can use the Transform function string (), which converts any type of value to a string, and the string () function follows the conversion rule: 1). If the value has the ToString () method, the method (with no parameters) is called to return the corresponding result 2). Returns "NULL" if the value is null 3). Returns "Undefined" if the value is undefined

7.Object type

The object in ECMAScript is actually a set of data and functions. objects can be created by using the new operator. In ECMAScript, if you cannot construct a function to pass parameters, you can omit the pair of parentheses that follow.

As shown below

var obj = new Object ();
var obj = new object;//But generally does not recommend this notation.

Each instance of object has the following properties and methods

Constructor holds the constructor for creating the current object

hasOwnProperty (PropertyName) is used to check whether a given property exists in the current object instance (not in the instance's prototype)

isPrototypeOf (object) is used to check if an incoming object is a prototype of another object

propertyIsEnumerable (PropertyName) is used to check whether a given property can use the For-in statement to sleep.

Tolacalstring () returns a string representation of the object that corresponds to the region of the execution environment.

ToString () returns the string representation of the object.

ValueOf () returns the string, numeric value, and Boolean value of the object that returns the original value of the specified object.

The ValueOf method definition differs for each JavaScript intrinsic object.

Object return value
Array The elements of the array are converted to strings, which are separated by commas and concatenated together. The operation is the same as the array.tostring and Array.join methods.
Boolean A Boolean value.
Date The stored time is the number of milliseconds that are counted from midnight January 1, 1970 UTC.
Function function itself.
Number numeric value.
Object The object itself. This is the default condition.
String The string value.

The Math and Error objects do not have a valueOf method.

Three. Functions

A. The function is declared by using the Functions keyword followed by a set of parameters and the body of the function.

function Sayhi (name,message) {

Alter ("Hello" +name+ "," +message);

}

function invocation: Called by the function name, followed by a pair of parentheses and arguments.

Sayhi ("Nike", "How is you today?");

Any code after the return statement in the function will never execute

The return statement can also have no return value, in which case the function will return a undefined value after it has stopped executing

function sum (num1,num2) {

return num1+num2;

Alter ("Hello");//will never be executed

}

SUM (5,10);

Two. JavaScript's function parameters

JavaScript's function parameters are different from other languages, it does not mind how many arguments are passed in, or what data type The parameter is passed in. The reason is that JavaScript's function parameters are internally represented by an array , which is always the array that the function receives, doesn't care what parameters are contained in the array, and does not have a parameter. This parameter array can be accessed by the arguments object in the body of the function to obtain each parameter passed to the function.

You can use the square bracket syntax to access each of his arguments (Arguments[0] The first parameter, Arguments[1] the second argument,. ...... )

By arguments the length property of the object, you can get how many arguments are passed to the function, and the named argument that does not pass the value is automatically assigned the undefined value (all parameters in the ECMAScript pass the value, it is not possible to pass the argument by reference)

The above functions can be overridden to use named parameters without displaying them :

function Sayhi () {

Alter ("Hello" +arguments[0]+ "," +arguments[1]);//arguments[0] corresponds to the name parameter

}

Named parameters can be used with the arguments object, and the value of arguments is always synchronized with the value of the corresponding named parameter. Modifying the value of a named parameter does not change the value of the arguments, and modifying the value of arguments changes the value of the named parameter.

function Doadd (num1,num2) {
arguments[1]=10;
alert (ARGUMENTS[0]+NUM2);
}
Doadd (0,20);

ECMAScript all parameters are passed values, it is not possible to pass arguments by reference

Three. ECMAScript function is not overloaded

Overloading refers to defining two functions with the same name, as long as the two defined signatures (the type and number of accepted parameters) are different.

ECMAScript two functions with the same name, and the function defined above overrides the function defined first.

function Addsomenumber (num) {

return num+100;

}

function Addsomenumber (num) {

return num+200;

}

var result = Addsomenumber (100); 300

Note: Unlike other languages, ECMAScript does not define separate data types for integer and floating-point values, and Numer types can be used to represent all values

There is no need to specify the return value of the function in ECMAScript, because any ECMAScript function can return any value at any time

The function parameter in the ECMAScript function is passed in the form of an array containing 0 or more values.

You can pass any number of arguments to the ECMAScript function, and you can access these parameters through the arguments object

Learning Notes (ii) JavaScript basic concepts (syntax, data types, control statements, functions)

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.