Home  >  Article  >  Web Front-end  >  Detailed explanation of js data types

Detailed explanation of js data types

小云云
小云云Original
2018-03-22 17:22:511238browse

ES5 simple data types (also called basic data types): Undefined, Null, Boolean, Number and String. There is also a complex data type - Object. Object is essentially composed of a set of unordered name-value pairs. ECMAScript does not support any mechanism for creating custom types, and all values ​​will end up being one of the 6 data types mentioned above.

1. typeof operator - detect the data type of a given variable
Using the typeof operator on a value may return one of the following strings:
"undefined" - if the value is not Definition;
"boolean"——If the value is a Boolean value;
"string"——If the value is a string;
"number"——If the value is a numeric value;
" object" - if this value is an object or null;
"function" - if this value is a function.
The following are several examples of using the typeof operator:
var message = "some string";
alert(typeof message); // "string"
alert(typeof(message)); // "string"
alert(typeof 95); // "number"
These examples illustrate that the operand of the typeof operator can be a variable or a numerical literal. Note that typeof is an operator, not a function, so the parentheses in the example are not required, although they can be used.

Sometimes the typeof operator returns confusing but technically correct values. For example, calling typeof null returns "object" because the special value null is considered a null object reference. Safari 5 and earlier and Chrome 7 and earlier return "function" when calling the typeof operator on a regular expression, while other browsers return "object" in this case. Technically speaking, functions in ECMAScript are objects, not a data type. However, functions do have some special properties, so it is necessary to distinguish functions from other objects through the typeof operator.

2.1 undefined type

The undefined type has only one value, which is the special undefined. This value was introduced to formally distinguish a null object pointer from an uninitialized variable. For variables that have not yet been declared, only one operation can be performed, which is to use the typeof operator to detect its data type. Let's look at the following example:

var message; // After this variable is declared, it has an undefined value by default
alert(typeof message); // "undefined"
alert(typeof age ); // "undefined"
The results show that executing the typeof operator on uninitialized and undeclared variables returns an undefined value. Because although the two variables are essentially different from a technical point of view, in fact it is impossible to perform real operations on either variable.

2.2 null type

The null type is a data type with only one value, and this special value is null. From a logical point of view, a null value represents a null object pointer, which is why using the typeof operator to detect a null value returns "object".
If the defined variable is going to be used to save objects in the future, it is best to initialize the variable to null rather than to another value.
In fact, the undefined value is derived from the null value, so ECMA-262 stipulates that their equality test should return true:
alert(null == undefined); //true
Here, located The equality operator (==) between null and undefined always returns true, but note that this operator converts its operands for comparison purposes.

Although null and undefined have this relationship, their uses are completely different. Under no circumstances is it necessary to explicitly set the value of a variable to undefined, but the same rule does not apply to null. In other words, as long as a variable that is intended to hold an object does not actually hold an object, you should explicitly let the variable hold a null value. Doing so not only reflects the convention of null as a null object pointer, but also helps to further distinguish null and undefined.

2.3 boolean type

The boolean type has only two literal values: true and false, which are case-sensitive.

Values ​​converted to false: false, "" (empty string), 0 and NaN, null, undefined

2.4 number type

number type: integer and floating point values.
Since saving floating point values ​​requires twice as much memory space as saving integer values, ECMAScript will lose no time in converting floating point values ​​into integer values. Obviously, if the decimal point is not followed by any digits, then the value can be saved as an integer value.
var floatNum1 = 1.; // No digits after the decimal point - parsed as 1
var floatNum2 = 10.0; // Integer - parsed as 10
The highest precision of floating point values ​​is 17 decimal places, But its accuracy when performing arithmetic calculations is far less than that of integers.

Regarding the problem that floating-point numerical calculations will produce rounding errors, one thing needs to be clear: This is a common problem when using floating-point calculations based on IEEE754 numerical values. ECMAScript is not unique; others use the same numerical values. Format languages ​​also have this problem.

The isFinite() function can determine whether a value is finite (whether it is between the minimum and maximum values). This function returns true if the argument is between the minimum and maximum values.

NaN, Not a Number, is a special value. This value is used to indicate that an operand that was supposed to return a value does not return a value (so that no error is thrown) . For example, in ECMAScript, dividing any number by 0 returns NaN and therefore does not affect the execution of other code. NaN itself has two unusual characteristics. First, any operation involving NaN (such as NaN/10) will return NaN, which may cause problems in multi-step calculations. Second, NaN is not equal to any value, including NaN itself. For example, the following code will return false: alert(NaN == NaN); //false
isNaN() After receiving a value, it will try to convert the value to a numeric value. Some values ​​that are not numeric are converted directly to numeric values, such as the string "10" or a Boolean value. Any value that cannot be converted to a numeric value will cause this function to return true. Please see the following example:
alert(isNaN(NaN)); //true alert(isNaN("10")); //false (can be converted to the value 10)
alert(isNaN("blue ")); //true (cannot be converted into a numerical value) alert(isNaN(true)); //false (can be converted into a numerical value 1)

isNaN() does also apply to objects. When the isNaN() function is called based on an object, the valueOf() method of the object is first called, and then it is determined whether the value returned by the method can be converted to a numeric value. If not, call the toString() method based on this return value, and then test the return value. This process is also the general execution process of built-in functions and operators in ECMAScript.

Numeric conversion: There are 3 functions that can convert non-numeric values ​​into numeric values: Number(), parseInt() and parseFloat().
The conversion function Number() can be used for any data type, while the other two functions are specifically used to convert strings into numerical values. These three functions will return different results for the same input.
The conversion rules of the Number() function are as follows:
 If it is a Boolean value, true and false will be 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, return 0.
 If it is undefined, return NaN.
 If it is a string, follow the following rules:
 If the string contains only numbers (including those preceded by a positive or negative sign), it will be converted to a decimal value, that is, "1" will becomes 1, "123" will become 123, and "011" will become 11 (note: leading zeros are ignored);
 If the string contains a valid floating point format, such as "1.1" , it will be converted to the corresponding floating point value (also, leading zeros will be ignored);
 If the string contains a valid hexadecimal format, such as "0xf", it will be converted to the same size The decimal integer value;
 If the string is empty (does not contain any characters), it is converted to 0;
 If the string contains characters other than the above format, it is converted is NaN.
 If it is an object, call the valueOf() method of the object, and then convert the returned value according to the previous rules. If the result of the conversion is NaN, call the object's toString() method, and then convert the returned string value again according to the previous rules.
Let’s give a few specific examples below.
var num1 = Number("Hello world!"); //NaN
var num2 = Number(""); //0
var num3 = Number("000011"); //11
var num4 = Number(true); //1
The parseInt() function is more commonly used when processing integers. When the parseInt() function converts a string, it ignores spaces in front of the string until it finds the first non-space character. If the first character is not a numeric character or a negative sign, parseInt() will return NaN; that is, using parseInt() to convert an empty string will return NaN (Number() returns 0 for null characters). If the first character is a numeric character, parseInt() will continue parsing the second character until all subsequent characters have been parsed or a non-numeric character is encountered. For example, "1234blue" will be converted to 1234, because "blue" will be completely ignored. Similarly, "22.5" would be converted to 22 because the decimal point is not a valid numeric character.
If the first character in the string is a numeric character, parseInt() can also recognize various integer formats. If the string begins with "0x" and is followed by numeric characters, it will be interpreted as a hexadecimal integer; if the string begins with "0" and is followed by numeric characters, it will be interpreted as an octal number. .
In order to better understand the conversion rules of the parseInt() function, some examples are given below:
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)
var num = parseInt("070");//In the ES5 JavaScript engine, parseInt() no longer has the ability to parse octal values
The parseInt() function provides the second parameter: the base used for conversion (i.e. how many bases) .
var num = parseInt("0xAF", 16); //175 var num1 = parseInt("AF", 16); //175
If 16 is specified as the second parameter, the string may not be With leading "0x".
Similar to the parseInt() function, parseFloat() also parses each character starting from the first character (position 0). And it is 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, but the second decimal point is invalid, so the string after it will be ignored. "22.34.5" will be converted to 22.34.
In addition to the valid first decimal point, the second difference between parseFloat() and parseInt() is that it always ignores leading zeros. parseFloat() recognizes all floating-point numerical formats discussed previously, including decimal integer formats. But strings in hexadecimal format will always be converted to 0. Since parseFloat() only parses decimal values, it has no usage of specifying the base with the second argument. One last thing to note: if the string contains a number that can be parsed as an integer (no decimal point, or all zeros after the decimal point), parseFloat() will return an integer. The following are some 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

2.5 String type

String in ECMAScript are immutable, that is, once strings are created, their values ​​cannot be changed. For example:
var lang = "Java";
lang = lang + "Script";
The variable lang in the above example initially contains the string "Java". The second line of code redefines the value of lang to "JavaScript". The process of implementing this operation is as follows: first create a new string that can hold 10 characters, then fill this string with "Java" and "Script", and the last step is to destroy the original string "Java" and "String" Script" because these two strings are no longer useful.
var age = 11; var ageAsString = age.toString(); // String "11"
var found = true; var foundAsString = found.toString(); // String "true"
Numeric values, Boolean values, objects and string values ​​(yes, every string also has a toString() method, which returns a copy of the string) all have toString() methods. But null and undefined values ​​do not have this method.
When you don't know whether the value to be converted is null or undefined, you can also use the conversion function String(), which can convert any type of value into a string. The String() function follows the following conversion rules:
 If the value has a toString() method, call the method (without parameters) and return the corresponding result;
 If the value is null, return "null";
 If the value is undefined, return "undefined".
Because null and undefined do not have a toString() method, the String() function returns the literal values ​​of these two values.
Tip: To convert a value to a string, you can use the plus operator to add it to a string ("").

2.6 Object type

Objects in ECMAScript are actually a collection of data and functions. Created by: var o = new Object();
Every instance of Object has the following properties and methods.
 constructor: Saves the function used to create the current object. For the previous example, the constructor is Object().
 hasOwnProperty(propertyName): used to check whether the given property exists in the current object instance. Among them, the property name (propertyName) as a parameter must be specified in the form of a string (for example: o.hasOwnProperty("name")).
 isPrototypeOf(object): Used to check whether the incoming object is the prototype of the incoming object.
 propertyIsEnumerable(propertyName): Used to check whether a given property can be enumerated using a for-in statement. Like the hasOwnProperty() method, the property name as a parameter must be specified in string form.
 toLocaleString(): Returns the string representation of the object, which corresponds to the region of the execution environment.
 toString(): Returns the string representation of the object.
 valueOf(): Returns the string, numerical or Boolean representation of the object. Usually the same as the return value of the toString() method.
Since Object is the basis of all objects in ECMAScript, all objects have these basic properties and methods.

Technically speaking, the behavior of objects in ECMA-262 does not necessarily apply to other objects in JavaScript. Objects in the browser environment, such as objects in the BOM and DOM, are host objects because they are provided and defined by the host implementation. ECMA-262 is not responsible for defining host objects, so host objects may or may not inherit from Object.

3. Note

(1) If any operand is compared with NaN, the result will be false.
(2) null == undefined will return true because they are similar values; but null === undefined will return false because they are different types of values.

The above is the detailed content of Detailed explanation of js data types. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn