"JavaScript advanced Programming" Reading notes---data types

Source: Internet
Author: User
Tags hasownproperty

There are 5 simple data types (also known as basic data types) in ECMAScript:Undefined, Null, Boolean, number, string, and object-complex data types, 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 95); "Number"

Note that TypeOf is an operator and not a function, so the parentheses in the example are not required, although they can be used .

Calling typeof null returns "Object" because the special value null is considered to be an empty object Reference.

Sometimes it is necessary to distinguish functions and other objects through the typeof operator.

Undefined type

The Undefined type has only one value, that is, a special Undefined. When you declare a variable using var but do not initialize it, the value of the variable is undefined, for example:
VAR message;
Alert (message = = undefined); True

Null type

The null type is the second data type with only one value, and this special value is null. From a logical point of view, a null value represents an empty object pointer, which is why the "object" is returned when using the TypeOf operator to detect null values, for example:
var car = null;
Alert (typeof car); "Object"

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, such as:
if (car! = null) {
Perform certain actions on the car object
}
In fact, the undefined value is derived from a null value, so ECMA-262 specifies that the equality test for them returns true:
Alert (Null = = undefined); True

Although null and undefined have such relationships, their use is completely different. As mentioned earlier, it is not necessary to explicitly set the value of a variable to undefined in any situation, but the same rule does not apply to NULL. In other words, as long as the variable that is intended to hold the object does not actually hold the object, you should explicitly let the variable hold the null value. Doing so not only manifests null as a convention for null object pointers, but also helps to further differentiate between null and undefined.

Boolean type

The Boolean type is the most used type in ECMAScript, which has only two literals: true and false.
These two values are not the same as numeric values, so true does not necessarily equal 1, and false does not necessarily equal 0.

Example of a Boolean value:
var found = true;
var lost = false;
Note that the literal value of the Boolean type True and false is case-sensitive. That is, True and false (as well as other mixed-case forms) are not Boolean values, but identifiers.

To convert a value to its corresponding Boolean value, you can call the transform function Boolean (), such as:
var message = "Hello world!";
var Messageasboolean = Boolean (message);

In this example, the string message is converted to a Boolean value that is stored in the Messageasboolean variable. You can call the Boolean () function on a value of any data type, and always return a Boolean value. The value returned is true or false, depending on the data type of the value to be converted and its actual value. The following table shows the various data types and their corresponding conversion rules.

These translation rules are important for understanding flow control statements (such as the IF statement) to automatically perform a corresponding Boolean conversion, see the following code:
var message = "Hello world!";
if (message) {
Alert ("Value is true");
}

Running this example, a warning box is displayed because the string message is automatically converted to the corresponding Boolean value (TRUE). Because of this automatic Boolean conversion, it is important to know exactly what variables are used in flow control statements. By using an object incorrectly instead of a Boolean value, it is possible to radically alter the process of the application.

Number Type

The number type should be the most interesting data type in ECMAScript, which uses the IEEE754 format to represent integers and floating point values (floating-point numbers are also known as double-precision values in some languages). To support various numeric types, ECMA-262 defines different numeric literal formats.

The most basic numeric literal format is a decimal integer, and a decimal integer can be entered directly into the code as follows:
var intnum = 55; Integer
In addition to decimal notation, integers can be represented by octal (base 8) or hexadecimal (base 16) literals.

1. Floating-point values
The so-called floating-point value is that the number must contain a decimal point, and must have at least one digit after the decimal. Although there can be no integers before the decimal point, we do not recommend this notation. Here are a few examples of floating-point values:
var floatNum1 = 1.1;
var floatNum2 = 0.1;
var floatNum3 =. 1; Valid, but not recommended

Because the memory space required to hold a floating-point value is twice times the value of the saved integer, ECMAScript will lose no chance in converting the floating-point value to an integer value. Obviously, if the decimal point is not followed by any number, then this value can be saved as an integer value. Similarly, if the floating-point value itself represents an integer (such as 1.0), the value is also converted to an integer, as shown in the following example:
var floatNum1 = 1.; No digits after the decimal point--resolves to 1
var floatNum2 = 10.0; integer--resolves to 10

For those large or small values, a floating-point numeric representation can be expressed in e notation (i.e. scientific notation). The value represented by the E notation equals the number in front of e multiplied by the exponential power of 10. The same is true of the format of e notation in ECMAScript, which is preceded by a numeric value (which can be an integer or a floating-point number), an uppercase or lowercase letter E, followed by an exponent in the power of 10, which is used to multiply the preceding number. Here is an example of a numeric value using e notation:
var floatnum = 3.125e7; equals 31250000
In this example, the floatnum of a variable represented by e notation is concise, but its actual value is 31250000.
Here, the actual meaning of E notation is "3.125 times 107".

the highest precision of a floating-point value is 17 decimal places , but it is far less accurate than an integer in arithmetic calculations. For example, the result of 0.1 plus 0.2 is not 0.3, but 0.30000000000000004. This small rounding error can result in the inability to test a specific floating-point value.

For example:
if (A + b = = 0.3) {//Do not do such a test!
Alert ("You got 0.3.");
}

2. Range of values
Due to memory limitations, ECMAScript cannot save all the values in the world. The minimum value that ECMAScript can represent is saved in Number.min_value -the value is 5e-324in most browsers, and the maximum value that can be represented is saved in Number.max_ value--In most browsers, this value is 1.7976931348623157e+308. If the result of a calculation results in a value that exceeds the range of JavaScript values, the value is automatically converted to a special Infinity value . Specifically, if the value is negative, it is converted to -infinity (negative infinity), and if the value is positive, it is converted to Infinity (positive infinity).
As mentioned above, if a calculation returns a positive or negative infinity value, the value will not continue to participate in the next calculation because infinity is not able to participate in the calculated value. To determine whether a value is poor (in other words, between the minimum and maximum values), you can use the isfinite () function . This function returns True when the parameter is between the minimum and maximum values, as shown in the following example:
var result = Number.MAX_VALUE + Number.MAX_VALUE;
Alert (isfinite (result)); False
Although certain values are rarely exceeded in calculations, it is possible and necessary to monitor these values when performing calculations of very small or large numbers.

3. NaN
NaN, that is, a non-numeric (not a number) is a special value that represents a case where an operand that would have returned a numeric value does not return a number (so that no error is thrown).

In ECMAScript, any value divided by 0 returns Nan①, so it does not affect the execution of other code.

The NaN itself has two unusual features. First, any operation involving Nan, such as NAN/10, will return Nan, a feature that can cause problems in a multi-step calculation. Second,nan is not equal to any value , including the Nan itself . For example, the following code returns false:
Alert (nan = = Nan); False
For these two characteristics of Nan, ECMAScript defines the IsNaN () function . This function takes a parameter, which can be any type, and the function will help us determine whether the parameter is "not a value". IsNaN () after receiving a value, it attempts to convert the value to a number. Some values that are not numeric are converted directly to numeric values, such as the string "10" or the Boolean value. Any value that cannot be converted to a number will cause the function to return true. Take a look at the following example:
Alert (IsNaN (NaN)); True
Alert (IsNaN (10)); False (10 is a numeric value)
Alert (IsNaN ("10")); False (can be converted to a value of 10)
Alert (IsNaN ("Blue")); True (cannot be converted to numeric value)
Alert (IsNaN (true)); False (can be converted to a value of 1)

4. Numeric conversions
There are 3 functions that can convert non-numeric values to numeric values: Number (), parseint (), and parsefloat ().

The first function, the transformation function number (), can be used for any data type, while the other two functions are specifically used to convert a string into a numeric value. These 3 functions will return different results for the same input.
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.
? If it is a null value, 0 is returned.
? If it is undefined, return nan.
? If it is a string, follow these rules:
? If the string contains only numbers (including cases preceded by a plus or minus sign), it is converted to a decimal value, that is, "1" becomes 1, "123" becomes 123, and "011" becomes 11 (note: The leading 0 is ignored);
? If the string contains 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 a valid hexadecimal format, 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.
? 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, 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 ("000011"); 11
var num4 = number (true); 1

First, the string "Hello world!" is converted to Nan because it does not contain any meaningful numeric values. The empty string is converted to 0. The string "000011" is converted to 11 because its leading 0 is ignored. Finally, the value of true is converted to 1.

The parseint () function converts a string more to see whether it conforms to a numeric pattern. It ignores the spaces in front of the string until the first non-whitespace character is found. 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 a null character). 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, "1234blue" 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 (the decimal, octal, and hexadecimal numbers discussed earlier). 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.
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 (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)

When parsing strings like octal literals using parseint (), ECMAScript 3 and 5 differ. For example:

ECMAScript 3 is considered 56 (octal), ECMAScript 5 is 70 (decimal)
var num = parseint ("070");
In the ECMAScript 3 JavaScript engine, "070" is treated as octal literal, so the converted value is 56 decimal.
In the ECMAScript 5 JavaScript engine, parseint () does not have the ability to parse octal values, so the leading 0 is considered invalid, thus treating the value as "70", resulting in a decimal 70. In ECMAScript 5, this is true even in non-strict mode.
To eliminate the confusion that can be caused by using the parseint () function, you can provide a second argument for this function: the cardinality (that is, how many) to use when converting. If you know that the value to parse is a string in hexadecimal format, specifying cardinality 16 as the second parameter guarantees the correct result, for example:
var num = parseint ("0xAF", 16); 175
In fact, if you specify 16 as the second argument, the string can be without the preceding "0x", as follows:
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.
Specifying the cardinality affects the output of the transformation. For example:
var num1 = parseint ("10", 2); 2 (by binary parsing)
var num2 = parseint ("10", 8); 8 (parsing by octal)
var num3 = parseint ("10", 10); 10 (resolution by decimal)
var num4 = parseint ("10", 16); 16 (parsing by hexadecimal)

Not specifying a cardinality means letting parseint () decide how to parse the input string, so in order to avoid error parsing, we recommend explicitly specifying the cardinality regardless of the circumstances.

Parsefloat () also parses each character starting with the first character (position 0). It is also parsed until the end of the string, or until an invalid floating-point numeric character is encountered. In other words, the string
A decimal point 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 will always ignore the leading 0. Parsefloat () can recognize all floating-point numeric formats discussed previously, and also include decimal integer formats. But the hexadecimal-formatted string is always converted to 0. Because Parsefloat () parses only the decimal value, it does not specify the usage of the cardinality with the second argument. Finally, note that if the 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 numeric values.
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

The string type is used to represent a sequence of characters consisting of 0 or more 16-bit Unicode characters, the string. The string can be represented by double quotation marks (") or single quotation marks ('), so the following two strings are written in a valid way:
var firstName = "Nicholas";

1. Character literals
The String data type contains some special character literals, also called escape sequences, that represent nonprinting characters, or characters that have other uses. These character literals are shown in the following table:

These character literals can appear anywhere in the string, and will be parsed as a character, as shown in the following example:
var text = "This was the letter sigma: \u03a3.";
In this example, the variable text has 28 characters, with an escape sequence of 6 characters representing a 1 character.
The length of any string can be obtained by accessing its long property, for example:
alert (text.length); Output 28
The number of characters returned by this property includes the number of 16-bit characters. If the string contains double-byte characters, the length property may not accurately return the number of characters in the string.

2. Characteristics of strings

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

For example:
var lang = "Java";
Lang = lang + "Script";
The variable lang in the example above starts with the string "Java". The second line of code redefined the value of Lang as a combination of "Java" and "Script", or "JavaScript." This is done by first creating a new string that can hold 10 characters, then populating the string with "Java" and "script", and the final step is to destroy the original string "Java" and the string "Script" because the two strings are useless. This process occurs in the background, and this is why it is very slow to stitch strings in some older browsers, such as Firefox, IE6, and so on, which have a version of less than 1.0. But later versions of these browsers have solved this inefficiency problem.

3. Converting to a string

There are two ways to convert a value to a string. The first is the toString () method that uses almost every value (the feature of this method is discussed in the 5th chapter). The only way to do this is to return the string representation of the corresponding value. Such as:
var age = 11;
var ageasstring = age.tostring (); String "11"
var found = true;
var foundasstring = found.tostring (); String "true"

Numeric, Boolean, object, and string values (yes, each string also has a ToString () method that returns a copy of the string) with the ToString () method. However, the null and undefined values do not have this method.
In most cases, calling the ToString () method does not have to pass arguments. However, when you call the ToString () method of a number, you can pass a parameter: the cardinality of the output value. By default, the ToString () method returns a string representation of a numeric value in decimal format. By passing the cardinality, toString () can output a string value expressed in binary, octal, hexadecimal, or any other valid binary format. Here are a few examples:

var num = 10;
Alert (num.tostring ()); "10"
Alert (num.tostring (2)); "1010"
Alert (num.tostring (8)); "12"
Alert (num.tostring (10)); "10"
Alert (num.tostring (16)); A

This example shows that by specifying the cardinality, the ToString () method changes the value of the output. The value 10, depending on the cardinality, can be converted to a different numeric format at output. Note that the default (no parameter) output value is the same as the output value for the specified cardinality 10 o'clock.
You can also use the Transform function string (), which can convert any type of value to a string, without knowing that the value to be converted is null or undefined. The String () function follows the following translation rules:
? If the value has the ToString () method, the method (with no parameters) is called and the corresponding result is returned;
? Returns "NULL" if the value is null;
? If the value is undefined, then "undefined" is returned.
Let's look at a few more examples below:
var value1 = 10;
var value2 = true;
var value3 = null;
var value4;
Alert (String (value1)); "10"
Alert (String (value2)); "True"
Alert (String (VALUE3)); "NULL"
Alert (String (VALUE4)); "Undefined"

There are 4 values converted: Numeric, Boolean, NULL, and undefined. The result of the conversion of numeric and Boolean values is the same as the result of calling the ToString () method. Because null and undefined do not have the ToString () method, the string () function returns the literal of both values.

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

Object type

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. Instead of creating an instance of type object and adding properties and/or methods to it, you can create a custom object, such as:
var o = new Object ();
In ECMAScript, if you do not pass arguments to the constructor, you can omit the pair of parentheses that follow. That is, in the case where the preceding example does not pass arguments, the parentheses can be omitted (but not recommended):
var o = new Object; Valid, but omit parentheses are not recommended
Just creating an instance of object is not useful, but the key is to understand an important idea: in ECMAScript, the object type is the basis of all its instances. In other words, any properties and methods that the object type has also exist in more specific objects.

Each instance of Object has the following properties and methods.
? Constructor: Holds the function that is used to create the current object. For the previous example, the constructor (constructor) is object ().
? hasOwnProperty (PropertyName): Used to check whether a given property exists in the current object instance (not in the instance's prototype). where the attribute name (PropertyName) as a parameter must be specified as a string (for example: O.hasownproperty ("name")).
? isPrototypeOf (object): Used to check whether an incoming object is a prototype of an incoming object (the 5th chapter discusses prototypes).
? propertyIsEnumerable (PropertyName): Used to check whether a given property can be enumerated using a for-in statement (discussed later in this chapter). As with the hasOwnProperty () method, the property name as a parameter must be specified as a string.
? toLocaleString (): Returns the string representation of the object that corresponds to the region where the execution environment is executed.
? 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.
Because object is the basis of all objects in ECMAScript, all objects have these basic properties and methods.

"JavaScript advanced Programming" Reading notes---data types

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.