Javascript data types are very simple, including only undefined, null, string, Boolean, number and object. Today we will explain these data types one by one to facilitate everyone's understanding and memory.
1. Classification
Basic data types: undefined, null, string, Boolean, number
Complex Data type: object
The attributes of object are defined in the form of unordered name and value pairs (name: value)
2. Detailed explanation
1. undefined: The undefined type has only one value: undefined. When a variable is declared using var but not initialized, the value of this variable is undefined.
A variable containing an undefined value is the same as Undefined variables are different. The following example can illustrate:
var demo1;//声明但未初始化 alert(demo1);//undefined alert(demo2);//报错,demo2 is not defined
2. null: The null type has only one value: null. From a logical point of view, the null value Represents a null object pointer.
If the defined variable is going to be used to hold an object in the future, it is best to initialize the variable to null rather than to another value. In this way, as long as the null value is directly detected, you can know whether the corresponding variable has saved a reference to an object, for example:
if(car != null) { //对car对象执行某些操作 }
In fact, the undefined value is derived from the null value, so ECMA -262 specifies that the test for their equality should return true.
alert(undefined == null); //true
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.
3. Boolean:
The Boolean type has two values: true and false. These two values are not the same thing as numeric values, so true It is not necessarily equal to 1, and false is not necessarily equal to 0.
It should be noted that the literal value of Boolean type is case-sensitive, that is to say, True and False (and other forms of mixed case) are not Boolean values, just identifiers.
Although there are only two literal values of the Boolean type, all types of values in JavaScript have values equivalent to these two Boolean values. To convert a value to its corresponding Boolean value, you can call the type conversion function Boolean(), for example:
var message = 'Hello World'; var messageAsBoolean = Boolean(message);
In this example, the string message is converted into a Boolean value, which Is stored in the messageAsBoolean variable. The Boolean() function can be called on a value of any data type and will always return a Boolean value. As for whether the returned value is true or false, it depends on the data type of the value to be converted and its actual value. The following table gives the conversion rules for various data types and their objects.
These conversion rules are very important to understand flow control statements (such as if statements) and automatically perform corresponding Boolean conversions, for example:
var message = 'Hello World'; if(message)//相当于if(Boolean(message)==true) { alert("Value is true");//Value is true }
Due to the existence of this automatically executed Boolean conversion, so it is crucial to know exactly what variables are used in flow control statements.
4. Number: integer and floating point
4.1 Integer: When performing calculations, all octal and hexadecimal numbers will be converted to decimal
4.2 Floating point: The highest precision of floating point values is 17 digits, so its precision is far inferior to integers in arithmetic calculations. For example: the result of 0.1 0.2 is not 0.3, but 0.30000000000000004. For example:
a=0.2; b=0.1; if(a+b==0.3){ alert("hello"); } else{ alert("hi"); }
The result will pop up "hi", so don't test a specific floating point value.
4.3 NaN: Not a Number. This value is used to indicate that an operand that was supposed to return a numerical value did not return a numerical value (so that an error will not be thrown).
NaN itself has two extraordinary 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:
alert(NaN == NaN); //false
There is an isNaN() function in JavaScript. This function accepts a parameter, which can be of any type, and the function will help us determine whether the parameter is "not a numeric value". After isNaN() receives a value, it will try to convert the value into 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. For example,
alert(isNaN(NaN)); //true alert(isNaN(10)); //false(10是一个数值) alert(isNaN("10")); //false(可能被转换为数值10) alert(isNaN("blue")); //true(不能被转换为数值) alert(isNaN("bule123")); //ture(不能被转换为数值) alert(isNaN(true)); //false(可能被转换为数值1)
has three functions that can convert non-numeric values into numeric values: Number(), parseInt() and parseFloat(). The first function, the conversion function Number(), can be used for any data type, while the other two functions are specifically used to convert strings into numbers. 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 replaced with 1 and 0 respectively
● If it is a numeric value, Just simply pass in and return
● If it is a null value, return 0
● If it is undefined, return NaN
● If it is a string, follow the following rules:
○ 如果字符串中只包含数字,则将其转换为十进制数值,即”1“会变成1,”123“会变成123,而”011“会变成11(前导的0被忽略)
○ 如果字符串中包含有效的浮点格式,如”1.1“,则将其转换为对应的浮点数(同样,也会忽略前导0)
○ 如果字符串中包含有效的十六进制格式,例如”0xf“,则将其转换为相同大小的十进制整数值
○ 如果字符串是空的,则将其转换为0
○ 如果字符串中包含除了上述格式之外的字符,则将其转换为NaN
● 如果是对象,则调用对象的valueOf()方法,然后依照前面的规则转换返回的值。如果转换的结果是NaN,则调用对象的toString()方法,然后再依次按照前面的规则转换返回的字符串值。
var num1 = Number("Hello World"); //NaN var num2 = Number(""); //0 var num3 = Number("000011"); //11 var num4 = Number(true); //1
由于Number()函数在转换字符串时比较复杂而且不够合理,因此在处理整数的时候更常用的是parseInt()函数,而处理浮点数的时候常用parseFloat()函数。
5、String
String类型用于表示由零或多个16位Unicode字符组成的字符序列,即字符串。字符串可以由单引号(')或双引号(")表示。
var str1 = "Hello"; var str2 = 'Hello';
任何字符串的长度都可以通过访问其length属性取得
alert(str1.length); //输出5
要把一个值转换为一个字符串有两种方式。第一种是使用几乎每个值都有的toString()方法。
var age = 11; var ageAsString = age.toString(); //字符串"11" var found = true; var foundAsString = found.toString(); //字符串"true"
数值、布尔值、对象和字符串值都有toString()方法。但null和undefined值没有这个方法。
多数情况下,调用toString()方法不必传递参数。但是,在调用数值的toString()方法时,可以传递一个参数:输出数值的基数。
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"
通过这个例子可以看出,通过指定基数,toString()方法会改变输出的值。而数值10根据基数的不同,可以在输出时被转换为不同的数值格式。
在不知道要转换的值是不是null或undefined的情况下,还可以使用转型函数String(),这个函数能够将任何类型的值转换为字符串。
String()函数遵循下列转换规则:
● 如果值有toString()方法,则调用该方法(没有参数)并返回相应的结果
● 如果值是null,则返回"null"
● 如果值是undefined,则返回”undefined“
6、object
对象其实就是一组数据和功能的集合。对象可以通过执行new操作符后跟要创建的对象类型的名称来创建。而创建Object类型的实例并为其添加属性和(或)方法,就可以创建自定义对象。
var o = new Object();
object类型所具有的任何属性和方法也同样存在于更具体的对象中,Object的每个实例都具有下列属性和方法:
● constructor(构造函数)——保存着用于创建当前对象的函数
● hasOwnProperty(propertyName)——用于检查给定的属性在当前对象实例中(而不是在实例的原型中)是否存在。其中,作为参数的属性名(propertyName)必须以字符串形式指定(例如:o.hasOwnProperty("name"))
● isPrototypeOf(object)——用于检查传入的对象是否是另一个对象的原型
● propertyIsEnumerable(propertyName)——用于检查给定的属性是否能够使用for-in语句来枚举
● toString()——返回对象的字符串表示
● valueOf()——返回对象的字符串、数值或布尔值表示。通常与toString()方法的返回值相同。
三、小测试
typeof(NaN) typeof(Infinity) typeof(null) typeof(undefined)
很多面试都会问到上面几个小问题哒~~
以上就是这6种javascript数据类型的介绍了,小伙伴们是否了解清楚了呢,希望看完本文后大家能有所提高。更多相关教程请访问JavaScript视频教程!

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

SublimeText3 Chinese version
Chinese version, very easy to use

mPDF
mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),