JavaScript article-----data types

Source: Internet
Author: User

There are 6 types of data in ECMAScript, including 5 basic data Types (undefined,null,boolean,number,string) and a complex data type (Object). "ES6 adds a more symbol data type, but it's not a discussion here first."

Undefined type

The undefined type has only one undefined value. When you declare a variable with VAR but do not initialize it, the value of the variable is automatically assigned the undefined value.

1 {2     var name; 3     Console.log (name);    // undefined 4 }
Null type

The null type also uses only one null value. A null value represents an empty object pointer at a logical angle, so an "object" is returned when a null value is detected using the TypeOf operator.

1 {2     var NULL ; 3     Console.log (typeof  dd);   4 }

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. 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 type has two literals: true and false. It is important to note that the literal value of Boolean literals, True and false, is case-sensitive. Both true and false are not Boolean values, they can only be considered identifiers.

All data type values in ECMAScript can be converted to their corresponding Boolean values by invoking the transform function, Boolean ().

1 {2     var bool =; 3     var _bool = Boolean (bool); 4     Console.log (_bool);    // true 5 }

The value returned by the calling conversion function is true or FALSE, depending on the type of data being converted and its actual value. The following table shows the various data types and their corresponding conversion rules:

Data type The value converted to true Value converted to False
Boolean True False
String Any non-empty string "" (empty string)
Number Any non-0 numeric value (including infinity) 0 and Nan
Object Any object Null
Undefined No Undefined
Number Type

The number type in ECMAScript uses the IEEE754 format to represent integers and floating-point numbers, supporting various numeric types. There are a few things you can discuss about the number type.

Floating point value

The so-called floating-point value is that the number must contain a decimal point, and must be at least a number after the decimal points. In order to reduce the memory footprint when storing numeric values (the memory space required to hold a floating-point value is twice times that of the integer value), ECMAScript converts the floating-point value to an integer value whenever possible.

1 {2     var float1 = 1.;    // no digits after the decimal point, resolved to 13     var float2 = 10.0    // integer, resolved to ten 4 }
Range of values

Due to the limitation of memory, the ECMAScript can hold a limited number of values, and the minimum and maximum values can be saved in Number.min_value and Number.man_value respectively. In most browsers, the two values are 5e-324 (science and Technology) and 1.7976931348623157e+308, respectively. If the result of a calculation exceeds this range of values, the value is automatically converted to a special Infinity (positive infinity) or-infinity (negative infinity). The infinity and-infinity can be judged by using the Isfinite () function. This function returns True when the parameter is between the minimum and maximum values.

1 {2     var result1 = 121; 3     var result2 = Number.MAX_VALUE + number.max_value; 4     Console.log (Isfinite (RESULT1));    // true 5     Console.log (Isfinite (RESULT2));    // false     6 }
NaN

NaN, that is, a non-numeric (not a number) is a special value that is used to denote an operation that returns a numeric value but does not return a numeric value (so that no error is thrown). Nan itself has the characteristics of two non-identical anomalies.

      • Any operation that involves Nan will return Nan, a feature that can cause problems in multi-step calculations.
      • Nan is not equal to any value, including Nan itself. That is, Nan = = Nan This statement always returns 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, attempts to convert the value to a number, and any value that cannot be converted to a number will cause the function to return true.

 1  {  Console.log (IsNaN (NaN)); // true     3  Console.log (IsNaN (100)); // false (100 is a numeric value)     4  Console.log (IsNaN (' 100 ')); // false (can be converted to numbers)     5  Console.log (IsNaN (' Blue ')); // true (cannot be converted to a numeric value)     6  Console.log (IsNaN (false )); // false (can be converted to numeric 1)  7 } 

IsNaN () is also applicable to objects, but not discussed here, below +.

numeric conversions

The three functions of number (), parseint (), and parsefloat () can convert a non-numeric value to a numeric value. The first transformation function number () can be used for any data type, while the other two functions are specifically used to convert a string to 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.
      • If it is a null value, 0 is returned.
      • If it is undefined, return nan.
      • If it is a string, follow the rules below.
        • If the string contains only numbers, it is converted to a decimal value (the leading 0 is ignored).
        • If the string contains a valid floating-point format, it is converted to the corresponding floating-point value (leading 0 is ignored).
        • 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, 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.
1 {2     varNUM1 = number (' Hello ');//convert to Nan, with no meaningful numeric value3     varnum2 = Number (");//Convert to 0, empty string4     varnum3 = number (' 00101 ');//Convert to 101, ignoring leading 05     varNUM4 = number (' true ');//Convert to 1, boolean conversion rule6     varNUM5 = number (' 0012.3 ');//Convert to 12.3, ignoring leading 07}

Comparing the number function to the complex and unreasonable conversion rules for strings, the parseint () function is relatively simple and reasonable for converting strings, so it is more commonly used. 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 a minus sign, parseint () returns Nan. In other words, converting an empty string with parseint () returns Nan. 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.

1 {2     var num1 = parseint (' 5656hello ');        // 5656 3     var num2 = parseint (");                // NaN 4     var num3 = parseint (' 33.4 ');            //  - 5     var = parseint (' num4 ');                //  - 6 }

You can provide a second parameter for parseint (): The cardinality used when converting (that is, how many binary). If you know that the value to parse is a string in hexadecimal format, you can specify cardinality 16 as the second parameter.

1 {2     var num1 = parseint (' 0xAf ', +);        // 175, 16 binary conversion 3     var num2 = parseint (' AF ', +);            // 175, when passing in the second parameter, the hexadecimal ' 0x ' can be omitted 4     var num3 = parseint (' AF ');                // NaN 5 }

Like the parseint () function, parsefloat () also parses each character starting with the first character. It is also parsed until the end of the string, or until an invalid floating-point numeric character is encountered. 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. Second, if the string contains a number that can be parsed as an integer, parsefloat () returns an integer.

1 {2     varNUM1 = parsefloat (' 456red ');//456, resolves to integers3     varnum2 = parsefloat (' 22.5 ');//22.54     varnum2 = parsefloat (' 123.123.12 ');//123.123, the first decimal point is valid, the second decimal point is invalid5     varnum3 = parsefloat (' 052.2 ');//52.5, ignoring leading 06     varnum3 = parsefloat (' 0.125e7 ');//31250000, Scientific counting method7}

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 (').

Character literal

The string data type contains some special character literals, also called escape sequences, that represent nonprinting characters, or characters that have other uses. The escape sequence can be anywhere in the string, and it will be parsed as a character. Escape sequences have these.

Literal quantity Meaning
\ n Line break
\ t Tab
\b Backspace
\ r Enter
\f Paper Feed
\\ Slash Slash
\‘ Single quotation mark ('), used in a string represented by single quotation marks. For example: ' He said,\ ' hey.\ '
\" Single quotation mark ('), used in a string represented by single quotation marks. For example: ' He said,\ ' hey.\ '
\xnn A character (where n is 0~f), expressed in hexadecimal code NN. For example, \x41 represents "A"
\unnnn A Unicode character (where n is 0~f) expressed in hexadecimal code nnnn. For example, \U03A3 represents the Greek character σ

The length of any string can be obtained by accessing its long property.

1 {2     var text = ' Some words. ' 3     Console.log (text.length);        // Ten 4 }

Character of the string

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

1 {2     var text = ' Some words '; 3     Text = text + ' for you. ';         // the original text string variable ' Some words ' and the newly created string value ' for you '. Connect, get the new string value ' Some words for you ', and populate the text variable with the new string value.  4 }

Convert to String

There are two ways to convert a value to a string.

The first approach is to use the ToString () method with almost every value (null and undefined only this method). This method returns the string representation of the corresponding value.

1 {2     var num = one; 3     var numtostring = num.tostring ();            // ' One ' 4     var true ; 5     var booltostring = bool.tostring ();            // ' true ' 6 }

When you call the ToString () method of a number, you can pass a parameter: The technique of outputting a numeric value. By default, the ToString () method returns a string representation of a numeric value in decimal format. By passing parameters, toString () can output string values in binary, octal, 16, and even any other valid binary format.

1 {2     varnum = 10;3Console.log (Num.tostring ());//' Ten '4Console.log (num.tostring (2));//' 1010 '5Console.log (num.tostring (8));//' a '6Console.log (num.tostring (10));//' Ten '7Console.log (Num.tostring (16));//' A '8}

The second method can be used in the case of any type of value (both null and undefined), which is called the transformation function string ().

      • If the value has 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 undefined, then "undefined" is returned.
1 {2     varvalue1 = 10;3     varvalue2 =true;4     varValue3 =NULL;5     varvalue4;6Console.log (String (value1));//' Ten '7Console.log (String (value2));//' true '8Console.log (String (VALUE3));//' null '9Console.log (String (value4));//' undefined ', value4 is not assigned so it is undefinedTen}
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. You can create a custom object by creating an instance of type object and adding properties and methods to it.

1 {2     var New Object (); 3     O.name = ' myname '; 4 }

In ECMAScript, the type of object is the basis of all its strength. In other words, any properties and methods that the object type has also exist in more specific objects. Therefore, each instance has the following properties and methods.

      • Constructor: Holds the function that is used to create the current object, also called the constructor. For the preceding object variable o, the 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.
      • Ispropertyof (object): Used to check whether an incoming object is a prototype of the current object.
      • propertyIsEnumerable (PropertyName): Used to check whether a given property can be enumerated using the For-in statement.
      • 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.

JavaScript article-----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.