Detailed explanation of JavaScript data types and their conversion
This article brings you a detailed explanation of JavaScript data types and their conversion. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
1. Introduction
Every value in JavaScript language belongs to a certain data type. There are seven data types in JavaScript:
Number: integer and decimal (such as 1 and 3.14).
String (string): text (such as Hello World).
Boolean: Two special values that represent authenticity, namely true (true) and false (false).
undefined: means "undefined" or does not exist.
null: Indicates a null value, that is, the value here is empty.
Object: A collection of various values.
Symbol
Symbol is a newly added basic data type in ES6. This article only introduces the first six types.
2. Detailed explanation of data types
1. Numeric value (number):
1.1 Integers and floating point numbers
JavaScript internal, All numbers are stored as 64-bit floating point numbers, even integers.
1 === 1.0 // true
1.2 Precision
In the international standard IEEE 754, the 64 binary bits of JavaScript floating point numbers, starting from the leftmost, the first digital sign bit determines the sign of a number ( 0 is a positive number, 1 is a negative number), the exponent part from 2 to 12 digits determines the size of the value, and the decimal part from 13 to 64 determines the accuracy of the value.
1.3 The base of numerical values
JavaScript provides four base representation methods for integers: decimal, hexadecimal, octal, and binary.
Decimal: Numeric value without leading 0.
Octal: A value with a prefix of 0o or 0O.
Hexadecimal: A value with a prefix 0x or 0X.
Binary: A value with prefix 0b or 0B.
1.4 NaN
NaN means Not a Number, which mainly occurs when there is an error in parsing a string into a number, such as:
618 - 'x' // NaN
NaN不等于任何值,包括它本身。:
NaN === NaN // false2 . String:
is quoted with '' or "". If it does not contain any content, it is an empty string with a length of 0. The one with spaces in it is called a space string, with a length of 1, and the two are different.
2.1 Multi-line string
If the string is divided into multiple lines, you can use a backslash at the end of each line, otherwise an error will be reported. In addition to using backslashes, you can also use the concatenation operator ( ) to concatenate multiple single-line strings. The results of the two methods are consistent. It is recommended to use the concatenation operator ( ).
var longString = 'Long \ long \ long \ string'; longString // "Long long long string"
var longString = 'Long ' + 'long ' + 'long ' + 'string'; longString // "Long long long string"
In ES6, backticks (`
) are added to write multi-line strings, and the length of this multi-line string will include the length of the carriage return.
2.2 Escape
Backslash () has special meaning in the string and is used to represent some special characters, so it is also called an escape character. Special characters that often need to be escaped with backslashes are:
0: null (u0000)
n: newline character (u000A)
r: Enter key (u000D)
t: Tab character (u0009)
': Single quotation mark (u0027)
-
": Double quotation mark (u0022)
\: Backslash (u005C)
2.3 length attribute
The length attribute returns the length of the string. This attribute is determined by the string itself and cannot be changed through assignment.
var s = 'mamamoo'; s.length // 7 s.length = 5; s.length // 7
3. boolean ):
Boolean values only have two values: "true" and "false". "True" is represented by the keyword true, and "false" is represented by the keyword false. If JavaScript expects A certain position should be a Boolean value, and the existing value at that position will be automatically converted to a Boolean value. The conversion rules are six values except undefined, null, false, 0, NaN, "" or '' (empty string) is converted to false, and other values are regarded as true.
4. undefined and null:
Both null and undefined can mean "none", meaning Very similar. The difference between the two is:
null is an object that represents "empty" and is 0 when converted to a numerical value; undefined is a primitive that represents "no definition here" Value, it is NaN when converted to a numerical value.
If a variable has no value, undefined is returned.
When there is an object object but you do not want to assign a value yet It is recommended to use null; when there is a non-object but you do not want to assign a value, it is recommended to use undefined.
5. Object:
5.1 Generation method
The object is simply a set of "key-value pairs", which is an unordered composite data collection.
The generation method is to use a large Parentheses wrap the key-value pair and assign it to the variable. The two key-value pairs are separated by commas. ":" is preceded by the key name, and ":" is followed by the key value. For example:
var obj = { foo: 'Hello', bar: 'World' };
5.2 Key Name and key value
对象的所有键名都是字符串,要加引号,不加也会自动转为字符串。如果键名不符合标识名的条件(比如第一个字符为数字,或者含有空格或运算符),且也不是数字,则必须加上引号,否则会报错。而键值是什么类型就用该类型的格式。
5.3 属性
对象的每一个键名又称为“属性”(property),它的“键值”可以是任何数据类型。
属性的读取
读取对象的属性,有两种方法,一种是使用点运算符,还有一种是使用方括号运算符。
var obj = { p: 'Hello World' }; obj.p // "Hello World" obj['p'] // "Hello World",[]内''一定要加
属性的删除delete(无value无key)
var obj = { p: 1 }; Object.keys(obj) // ["p"] delete obj.p // true obj.p // undefined Object.keys(obj) // []
属性的查看Object.keys
var obj = { key1: 1, key2: 2 }; Object.keys(obj); // ['key1', 'key2']
属性是否存在:in
in运算符用于检查对象是否包含某个属性(注意,检查的是键名,不是键值),如果包含就返回true,否则返回false。
属性的遍历:for...in 循环
var obj = {a: 1, b: 2, c: 3}; for (var i in obj) { console.log('键名:', i); console.log('键值:', obj[i]); } // 键名: a // 键值: 1 // 键名: b // 键值: 2 // 键名: c // 键值: 3
三、如何知道变量类型?
使用type of可得变量的数据类型,如:
var t = 619; type of t;//"number"
特别注意的是:
当数据类型为null时,用type of打出的数据类型却是'object'。
当定义了一个函数时,用type of打出的数据类型却是'function'。
四、数据类型的转换
4.1 转为string
使用toString()
var t = 619; t.toString();//"619"
null没有toString这个API,不能使用toString,会报错
var n = null; n.toString; //Uncaught TypeError: Cannot read property 'toString' of null
undefined也会报错
var n = undefined; n.toString(); //Uncaught TypeError: Cannot read property 'toString' of undefined
object使用toString会得到"[object Object]"。
var object = {name:"po"}; object.toString() //"[object Object]"
通过与空字符串相加(+"")也能转化为字符串类型,且null、undefined也适用。
使用window.String()
window.String(null)//"null"
为什么1 + '1' = '11'?
这是因为当两个不同数据类型相加时,会优先选择转化为字符串,所以1 + '1'相当于1.toString() + '1',于是结果为两个字符串1相加,即字符串11。
4.2 转为布尔
使用Boolean()
Boolean(0)//false Boolean('')//false Boolean(' ')//true
使用!!
!! ''//false !! ' '//true
五个falsy值:0、NaN、空字符串、null、undefined
4.3 转为Number
使用Number()
Number('1')//1
使用parseInt()
//第二位参数要写,是表示进制使用parseFloat()
parseFloat('1.23')//1.23
使用 -0
'1'-0//1
使用 +
+ null//0
The above is the detailed content of Detailed explanation of JavaScript data types and their conversion. For more information, please follow other related articles on the PHP Chinese website!

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.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing


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

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft