Home Web Front-end JS Tutorial Detailed explanation of js data types

Detailed explanation of js data types

Mar 22, 2018 pm 05:22 PM
javascript type Detailed explanation

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 of this Website
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Detailed explanation of obtaining administrator rights in Win11 Detailed explanation of obtaining administrator rights in Win11 Mar 08, 2024 pm 03:06 PM

Windows operating system is one of the most popular operating systems in the world, and its new version Win11 has attracted much attention. In the Win11 system, obtaining administrator rights is an important operation. Administrator rights allow users to perform more operations and settings on the system. This article will introduce in detail how to obtain administrator permissions in Win11 system and how to effectively manage permissions. In the Win11 system, administrator rights are divided into two types: local administrator and domain administrator. A local administrator has full administrative rights to the local computer

Detailed explanation of division operation in Oracle SQL Detailed explanation of division operation in Oracle SQL Mar 10, 2024 am 09:51 AM

Detailed explanation of division operation in OracleSQL In OracleSQL, division operation is a common and important mathematical operation, used to calculate the result of dividing two numbers. Division is often used in database queries, so understanding the division operation and its usage in OracleSQL is one of the essential skills for database developers. This article will discuss the relevant knowledge of division operations in OracleSQL in detail and provide specific code examples for readers' reference. 1. Division operation in OracleSQL

Detailed explanation of the role and usage of PHP modulo operator Detailed explanation of the role and usage of PHP modulo operator Mar 19, 2024 pm 04:33 PM

The modulo operator (%) in PHP is used to obtain the remainder of the division of two numbers. In this article, we will discuss the role and usage of the modulo operator in detail, and provide specific code examples to help readers better understand. 1. The role of the modulo operator In mathematics, when we divide an integer by another integer, we get a quotient and a remainder. For example, when we divide 10 by 3, the quotient is 3 and the remainder is 1. The modulo operator is used to obtain this remainder. 2. Usage of the modulo operator In PHP, use the % symbol to represent the modulus

Detailed explanation of the linux system call system() function Detailed explanation of the linux system call system() function Feb 22, 2024 pm 08:21 PM

Detailed explanation of Linux system call system() function System call is a very important part of the Linux operating system. It provides a way to interact with the system kernel. Among them, the system() function is one of the commonly used system call functions. This article will introduce the use of the system() function in detail and provide corresponding code examples. Basic Concepts of System Calls System calls are a way for user programs to interact with the operating system kernel. User programs request the operating system by calling system call functions

How to create a video matrix account? What types of matrix accounts do it have? How to create a video matrix account? What types of matrix accounts do it have? Mar 21, 2024 pm 04:57 PM

With the popularity of short video platforms, video matrix account marketing has become an emerging marketing method. By creating and managing multiple accounts on different platforms, businesses and individuals can achieve goals such as brand promotion, fan growth, and product sales. This article will discuss how to effectively use video matrix accounts and introduce different types of video matrix accounts. 1. How to create a video matrix account? To make a good video matrix account, you need to follow the following steps: First, you must clarify what the goal of your video matrix account is, whether it is for brand communication, fan growth or product sales. Having clear goals helps develop strategies accordingly. 2. Choose a platform: Choose an appropriate short video platform based on your target audience. The current mainstream short video platforms include Douyin, Kuaishou, Huoshan Video, etc.

Detailed explanation of Linux curl command Detailed explanation of Linux curl command Feb 21, 2024 pm 10:33 PM

Detailed explanation of Linux's curl command Summary: curl is a powerful command line tool used for data communication with the server. This article will introduce the basic usage of the curl command and provide actual code examples to help readers better understand and apply the command. 1. What is curl? curl is a command line tool used to send and receive various network requests. It supports multiple protocols, such as HTTP, FTP, TELNET, etc., and provides rich functions, such as file upload, file download, data transmission, proxy

Learn more about Promise.resolve() Learn more about Promise.resolve() Feb 18, 2024 pm 07:13 PM

Detailed explanation of Promise.resolve() requires specific code examples. Promise is a mechanism in JavaScript for handling asynchronous operations. In actual development, it is often necessary to handle some asynchronous tasks that need to be executed in sequence, and the Promise.resolve() method is used to return a Promise object that has been fulfilled. Promise.resolve() is a static method of the Promise class, which accepts a

Detailed analysis of C language learning route Detailed analysis of C language learning route Feb 18, 2024 am 10:38 AM

As a programming language widely used in the field of software development, C language is the first choice for many beginner programmers. Learning C language can not only help us establish the basic knowledge of programming, but also improve our problem-solving and thinking abilities. This article will introduce in detail a C language learning roadmap to help beginners better plan their learning process. 1. Learn basic grammar Before starting to learn C language, we first need to understand the basic grammar rules of C language. This includes variables and data types, operators, control statements (such as if statements,

See all articles