


A brief introduction to implicit type conversion of JavaScript data types_javascript skills
JavaScript data types are divided into six types, namely null, undefined, boolean, string, number, and object. object is a reference type, and the other five are basic types or primitive types. We can use the typeof method to print out which type something belongs to. To compare variables of different types, you must first convert the type, which is called type conversion. Type conversion is also called implicit conversion. Implicit conversions usually occur with the operators addition, subtraction, multiplication, division, equals, and less than, greater than, etc. .
typeof '11' //string typeof(11) //number '11' < 4 //false
This chapter separately introduces implicit data type conversion in JavaScript. A good grasp of it can simplify many operations in practical applications.
See the following code example:
var arr = [5]; console.log(arr+"");
The above code is an operation to implicitly convert an array into a string. Isn’t it much simpler than the following method:
var arr = [5]; console.log(arr.toString());
Implicit data type conversions like the above are widely used in actual coding. Let’s get to the point.
1. Data type conversion between value types:
For data types in JavaScript, please refer to the chapter "Detailed explanation of JavaScript data types".
(1). Numbers and strings use the + operator:
If you use the + operator to operate numbers and strings, the numbers will be converted to strings first, and then string concatenation operations will be performed:
var antzone = "antzone"; var num = 8; console.log(antzone+num);
(2). + operator operation involving Boolean values:
If there is a Boolean type involved, the Boolean value will first be converted into the corresponding number or string, and then the corresponding string connection or arithmetic operation will be performed.
var bool = true; var num = 8; console.log(bool + num);
The above code first converts true to the number 1, and then performs arithmetic addition.
var bool = true; var num = "8"; console.log(bool + num);
The above Boolean value will be converted into the corresponding string form "true", and then string concatenation is performed.
(3). Subtraction operation:
If a subtraction operation is performed, both operands will be converted to numbers first, and then the arithmetic operation will be performed:
var bool = true; var num = "8"; console.log(bool - num);
true will be converted to the number 1, the string "8" will be converted to the number 8, and then arithmetic operations will be performed.
The same applies to the conversions of multiplication, division, greater than, less than and subtraction, so I won’t give examples anymore.
(4).==Equality operation:
undefined and null are special. They both use the == operator to return true.
console.log(undefined==null);
When comparing other value types, the operands will be converted into numbers
console.log("3"==3);
The above code will convert the string "3" into a number and then compare it.
console.log("1"==true);
The above code will convert "1" and true into numbers respectively, and then compare them.
2. Convert reference type to value type:
Converting reference types (objects) to value types is much more complicated. The distribution is introduced below.
The two methods of object inheritance can help us realize the conversion function from object to value type:
(1).toString() method.
(2).valueOf() method.
Normally, we think that to convert an object into a string, you need to call the toString() method, and to convert an object into a number, you need to call the valueOf() method, but it is not that simple when it is actually applied. See the following code example:
var obj = { webName: "脚本之家", url:"softwhy.com" } console.log(obj.toString());
As can be seen from the above code, the toString() method does not convert the object into a string that reflects this object.
var arr = [1, 2, 3]; console.log(arr.valueOf());
As can be seen from the above code, the valueOf() method does not convert the object into a number that reflects this object.
var arr = [1, 2, 3]; console.log(arr.toString());
数组对象的toString()方法能够将数组转换为能够反映此数组对象的字符串。
总结如下:
(1).有些对象只是简单继承了toString()或者valueOf()方法,比如第一个例子。
(2).有些对象则不但是继承了两个方法,而且还进行了重写。
所以有些对象的方法能够达成转换成字符串或者数字的目标,有些则不能。
调用toString()或者valueOf()将对象转换成字符串或者数字的规则如下:
调用toString()时,如果对象具有这个方法,则调用此方法;如果此方法返回一个值类型数据,那么就返回这个值类型数据,然后再根据所处的上下文环境进行相关数据类型转换。如果没有toString(),或者此方法返回值并不是一个值类型数据,那么就会调用valueOf()(如果此方法存在的话),如果valueOf()返回一个值类型数据,那么再根据所处的上下文环境进行相关的数据类型转换。
进一步说明:
(1).上面介绍了通常默认情况下valueOf()和toString()方法的作用(将对象转换为数字或者字符串),但是需要注意的是,这并不是硬性规定,也就是说并不是valueOf()方法必须要返回数字或者toString()方法必须要转换为字符串,比如简单继承的这两个方法就无法进行实现转换为数字和字符串的功能,再比如,我们可以自己称谢这两个方法,返回值也没有必要是数字或者字符串。
(2).还有需要特别注意的一点就是,很多朋友认为,转换为字符串首先要调用toString()方法, 其实这是错误的认识,我们应该这么理解,调用toString()方法可以转换为字符串,但不一定转换字符串就是首先调用toString()方法。
看如下代码实例:
var arr = []; arr.valueOf = function () { return "1"; } arr.toString = function () { return "2"; } console.log(arr + "1");
上面的代码中,arr是要被转换为字符串的,但是很明显是调用的valueOf()方法,而没有调用toString()方法。有些朋友可能会有这样的质疑,难道[2]这样的数字转换成字符串"2",不是调用的toString()方法吗。
代码如下:
var arr = [2]; console.log(arr + "1");
其实过程是这样的,首先arr会首先调用valueOf()方法,但是数字的此方法是简单继承而来,并没有重写(当然这个重写不是我们实现),返回值是数组对象本身,并不是一个值类型,所以就转而调用toString()方法,于是就实现了转换为字符串的目的。
总结如下:
大多数对象隐式转换为值类型都是首先尝试调用valueOf()方法。但是Date对象是个例外,此对象的valueOf()和toString()方法都经过精心重写,默认是调用toString()方法,比如使用+运算符,如果在其他算数运算环境中,则会转而调用valueOf()方法。
代码实例如下:
var date = new Date(); console.log(date + "1"); console.log(date + 1); console.log(date - 1); console.log(date * 1);
以上内容是小编给大家介绍的JavaScript数据类型之隐式类型转换的全部内容,希望大家喜欢。

Both Python and JavaScript's choices in development environments are important. 1) Python's development environment includes PyCharm, JupyterNotebook and Anaconda, which are suitable for data science and rapid prototyping. 2) The development environment of JavaScript includes Node.js, VSCode and Webpack, which are suitable for front-end and back-end development. Choosing the right tools according to project needs can improve development efficiency and project success rate.

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

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.


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

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),

SublimeText3 Linux new version
SublimeText3 Linux latest version

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

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

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.
