JS Basics Review: The syntax of ECMAScript (ii)

Source: Internet
Author: User

There are five simple data types (also known as basic data types) in ECMAScript: Undefined, Null, Boolean, number, String

ECMAScript also has a complex data type--object,object essentially consists of a set of unordered name-value pairs.

ECMAScript does not support any mechanism for creating custom types, and all values will eventually be one of the above six data types, and since ECMAScript's data types are dynamic, there is no need to define additional data types.

Prison ECMAScript are loosely typed and therefore require a means to detect the data type of a given variable, and typeof is the operator responsible for providing this information.

The typeof operand can be either a variable or a numeric literal, and typeof is an operator rather than a function, so you can add parentheses when you use it.

Using the typeof operator on a value may return one of the following strings:

"Undifined"--the value is undefined

"Boolean"--this value is a Boolean type

"String"--the value is a string

"Number"--the value is numeric

"Object"--the value is an object or null (a special value of NULL is considered an empty object reference)

"Function"--This value returns "function" when calling the TypeOf operator for a function (SAFARI5 and previous versions, Chrome7, and previous versions, and other browsers returning "object")

From a technical point of view, a function is an object in ECMAScript, not a data type, but the function does have some special properties, so it is necessary to differentiate functions and other objects through the typeof operator.

The undefined type has only one value, that is, a special undefined, and the value of this variable is undefined when the variable is declared with Var but not initialized.

In general, there is no need to set a variable to undefined, the literal value undefined is usually used for comparison, before the third version of ECMA-262 does not have this value, the third version introduced it to formally distinguish between null object pointers and uninitialized variables.

You can only perform one operation on a variable that has not been declared, that is, using the TypeOf operator to detect its data type (calling delete on an undeclared variable does not cause an error, but it has no practical meaning).

Calling the TypeOf operator on a variable that has not been declared also returns the undefined value, although it differs fundamentally from the uninitialized value.

Even if the uninitialized variable is automatically assigned the undefined value, it is still wise to display the initialization variable, and if it does, then when the typeof operator returns the undifined value, it will be able to know that the variable is not declared and not yet initialized.

A null type has only one value, that is, a special null, and from a logical point of view, a null value represents an empty object pointer, which is why an object is returned when a null value is detected using the TypeOf operator.

If the defined variable is intended to be used to hold the object in the future, it is better to initialize the variable to null instead of the other value, so that if you check the null value directly, you will know whether the corresponding variable has saved a reference to the object.

In fact, the undefined value is derived from a null value, so the equality test for both in ECMA-262 returns True, although there are such relationships, but their purpose is completely different.

As long as the variable that is intended to hold the object does not actually hold the object, it should be clear that the variable holds a null value, which not only manifests null as a convention for null object pointers, but also helps to further differentiate between null and undefined.

The Boolean type is the most common type used in ECMAScript, which has only two literals: "True" and "false".

Boolean literals are case-sensitive, and values of all types in ECMAScript have values equivalent to these two Boolean values.

To convert a value to its corresponding Boolean value, you can call the Transform function Boolean (), and the various data types and their corresponding conversion rules are as follows:

Boolean:true (returns True), False (returns false)

String: Any non-empty string (returns True), "" (returns False)

Number: Any non-0 value/Including infinity (returns True), 0, and Nan (returns false)

Object: Any object (returns True), Null (return FALSE)

UNDEFINED:N/A (returns True), Undefined (return false)--N/A is not applicable abbreviation, meaning "Not applicable"

These translation rules are important for understanding the automatic execution of a Boolean transformation by a control flow statement, and using an object instead of a Boolean value can radically alter the process of the application.

The number type uses the IEEE754 format to represent integers and floating-point values, and in order to support various numeric types, ECMA-262 defines different numeric literal formats:

Decimal literals (all numeric values in eight and hexadecimal will eventually be converted to decimal values when doing arithmetic operations)

Octal literals (the first digit is 0, followed by the octal number sequence 0-7, if the sequence exceeds the octal range, the leading 0 is omitted as a decimal integer, and the octal integer is invalid in strict mode, causing the supported JavaScript engine to throw an error)

Hexadecimal literals (the first two bits are 0x, followed by the hexadecimal digits 0-9 and a-f, the letters are case-insensitive)

Given the way that JavaScript preserves values, you can save positive 0 (+0) and negative 0 (-0), and positive and negative 0 are considered equal.

A decimal point must be included in the float value, and there must be at least one digit after the point, and no integer before the decimal point, but this is not recommended.

Because the memory space required to hold the floating-point value is twice times the value of the saved integer, ECMAScript will lose no chance to convert the floating-point value to an integer value: No number after the decimal point, and the floating point itself represents an integer.

It is also possible to use a floating-point value represented by scientific notation to represent a large or very small number, and the number represented by scientific notation is equal to the value in front of e multiplied by the exponential power of 10, where the e-case is arbitrary.

The highest precision for floating-point numbers is 17 decimal places, but floating-point calculations based on IEEE754 values are generally computationally inaccurate, so never test a particular floating-point value.

Due to memory limitations, ECMAScript cannot save all values.

The minimum value that ECMAScript can represent is saved in Number.min_value, which is 5e-324 in most browsers.

The maximum value that ECMAScript can represent is saved in Number.MAX_VALUE, which is 1.7976931348623157e+308 in most browsers.

If the result of a calculation exceeds that range, then that value is automatically converted to a special Infinity value, or Infinity (positive infinity) If a positive number returns-infinity (negative infinity) if negative.

Access to number.negative_infinity and number.positive_infinity can be-infinity and infinity.

You can use the Isfinite () function if you want to confirm that a value is in the range of positive and negative infinity, and if the function's arguments return true between positive and negative infinity.

Nan is a non-numeric value (not a number) is a special value that represents a case where the operand that should have returned a numeric value does not return a value (so that no error is thrown).

In other programming languages, dividing any number by 0 will result in an error, and Nan will be returned in ECMAScript, thus not affecting the execution of other code.

Any operation that involves Nan will return Nan, a feature that can cause problems in a multi-step calculation, and Nan is not equal to any value, including itself.

For the above features ECMAScript defines the isNaN () function, which takes an argument and attempts to convert it to a numeric value, which returns true if it cannot be converted to a number:

Alert (IsNan (NaN));//true

alert (IsNan);//false (value 10)

Alert (IsNan ("ten"));//false (can be converted to a value of 10)

Alert (IsNan ("Blue"));//true (cannot be converted to a numeric value)

Alert (IsNan (true));//false (can be converted to a value of 1)

IsNaN () also applies to objects, and when called on an object, the object's valueof () method is called first, then the value can be returned, and if not, the ToString () method is called again based on the return value, and the return value is tested. This process is also the general execution flow of built-in functions and operators in ECMAScript.

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

The first function 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 rule for the number () function is as follows (the operation of the unary plus operator is the same as the function):

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;

If it is a null value, returns 0;

If it is undefined, return nan;

If it is a string, follow these rules:

Converts a string to a decimal value (ignoring the leading 0) if it contains only numbers (including cases preceded by a plus or minus sign)

If the string contains a valid floating-point format, it is converted to a floating-point value (ignoring leading 0)

If the string contains a valid hexadecimal format, it is converted to a decimal integer value of the same size

If the string is empty, convert it to 0

If the string contains characters other than the above format, it is converted to Nan

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

Because the number () function is complex and unreasonable when converting strings, the parseint () function is more commonly used when working with integers.

The parseint () function, when converting a string, is more likely to see if it conforms to a numeric pattern, ignoring the space preceding the string until it finds the first non-whitespace character.

If the first character is not a numeric character or a minus sign, parseint () returns Nan, and if the first character is a numeric character, it continues parsing until a non-numeric character position is encountered.

var num1=parseint ("1234blue");//1234

var num2=parseint ("");//nan

var num3=parseint ("0xA");//10 (hexadecimal number)

var num4=parseint ("22.5");//22

var num5=parseint ("070");//56 (octal number)

var num6=parseint ("70");//70 (decimal number)

var num7=parseint ("0xf");//15 (hexadecimal number)

Although the parseint () function recognizes a variety of integer formats, ECMASCRIPT3 and 5 differ when processing octal numbers.

In ECMAScript3, "070" is treated as octal literal, while ECMAScript5 already does not have the ability to parse octal values, so it ignores the leading 0 and converts it directly to a decimal value.

To eliminate the confusion that can be caused when using the parseint () function, you can give it a second argument: the cardinality (that is, how many) to use for the conversion to ensure that the correct result is obtained.

The parsefloat () function is parsed from the first character until an invalid floating-point number character is encountered, meaning that the first decimal point in the string is valid but the second decimal point is invalid.

The parsefloat () function always ignores the leading 0, which recognizes the floating-point numeric format and the decimal integer format, but the hexadecimal-formatted string is always converted to 0.

The parsefloat () function resolves only decimal values, so it does not specify the usage of cardinality with the second argument, and returns an integer if the string contains a value that can be resolved to an integer.

var num1=parsefloat ("1234blue");//1234 (integer)

var num2=parsefloat ("0xA");//0 (hexadecimal number cannot be resolved, all hexadecimal numbers will be resolved to 0)

var num3=parsefloat ("22.5");//22.5

var num4=parsefloat ("22.34.5");//22.34 (Invalid second decimal point)

var num5=parsefloat ("0908.5");//908.5 (leading 0 is always ignored)

var num6=parsefloat ("3.125e7");//31250000 (scientific counting method)

The string type is used to represent a sequence of characters consisting of 0 or more 16-bit Unicode characters, that is, a string.

Strings can be represented by single or double quotes, and single and double quotes in PHP affect the way strings are interpreted differently, not in ECMAScript, but note that the left and right quotes must match.

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

\ n newline \ t tab \b Space \ r Enter \f feed \ Slash \ ' single quote \ ' double quote

\xnn a character in hexadecimal code nn (where n is 0-f), for example: \x41 means "a"

\UNNNN A Unicode character (where n is 0-f) expressed in hexadecimal code nnnn, for example: \u03a3 represents Greek characters ∑

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

The length of any string can be obtained by accessing its long property, the number of characters returned by this property includes the number of 16-bit characters, and if the string contains double-byte characters, the length property may not accurately return the number of characters in the string.

The strings in ECMAScript are immutable, that is, when 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.

This process occurs in the background, which is why some older browsers are stitching strings in a slow way, but their high version has solved the problem.

There are two ways to convert a value to a string: the ToString () method and the string () function.

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

In most cases, calling the ToString () method does not have to pass arguments, but it can also pass the cardinality of the output value as a parameter, which can be any valid binary format, and the output value of the default no parameter is the same as the output value for the specified cardinality 10 o'clock.

You can use the string () function to convert any type of value to a string without knowing that the value to be converted is null or undefined.

If the value has the ToString () method, the method is called (with no arguments) and the corresponding result is returned, "null" if the value is null, or "undefined" if the value is undefined.

To convert a value to a string, you can use the plus operator to add it to a string ("").

The object in ECMAScript 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, for example: Var o=new object ();

You create a custom object by creating an instance of type object and adding properties and methods to it.

In ECMAScript, if you do not pass parameters to the constructor, you can omit the next pair of parentheses, but this is not recommended.

In ECMAScript, the object type is the basis of all its instances, and any properties and methods that the object type has also exist in more specific objects:

Constructor: holds the function for creating the current object, which is the constructor object () for the above example;

hasOwnProperty (PropertyName): Used to check whether a given property exists in the current object instance, where the property name (PropertyName) as a parameter must be specified as a string;

isPrototypeOf (object): Used to check if an incoming object is a prototype of an incoming object;

propertyIsEnumerable (PropertyName): Used to check whether a given property can be enumerated using a for-in statement, where the property name (PropertyName) as a parameter must be specified as a string;

toLocaleString (): Returns the string representation of an object that corresponds to the region of the execution environment;

ToString (): Returns the string representation of the object;

ValueOf (): Returns the string, numeric, or Boolean representation of an object, usually the same as the return value of the ToString () method.

In terms of technology, the behavior of the ECMA-262 object does not necessarily apply to other objects in JavaScript.

Objects in the browser environment, such as objects in the BOM and Dom, belong to the host object because they are provided and defined by the host implementation.

ECMA-262 is not responsible for defining the host object, so the host object may or may not inherit object.

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.