search
HomeWeb Front-endFront-end Q&AWhat are the two types of data type conversion in JavaScript?

What are the two types of data type conversion in JavaScript?

Feb 23, 2022 pm 06:50 PM
javascriptData type conversion

There are two types of data type conversion in JavaScript: 1. Explicit type conversion (also called forced type conversion), which mainly converts data by using JavaScript’s built-in functions; 2. Implicit type conversion, which refers to JavaScript based on The computing environment automatically converts the value's type.

What are the two types of data type conversion in JavaScript?

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

JavaScript is a weakly typed dynamically typed language. Variables have no type restrictions and can be assigned any value at any time.

var x = y ? 1 : 'a';

In the above code, whether the variable x is a numerical value or a string depends on the value of another variable y. When y is true, x is a numeric value; when y is false, x is a string. This means that the type of x cannot be known at compile time and must wait until runtime.

Although the data type of the variable is uncertain, various operators have requirements for the data type. If the operator finds that the type of the operator does not match the expected type, it will automatically convert the type. For example, the subtraction operator expects that the left and right operators should be numeric values, and if not, it will automatically convert them to numeric values.

'4' - '3' // 1

In the above code, although two strings are subtracted, the result value 1 will still be obtained. The reason is that JavaScript automatically converts the operator into a numerical value.

Data type conversion in javascript

Data type conversion in js is generally divided into two types, namely forced type conversion and implicit type Conversion (using js weak variable type conversion).

  • Explicit type conversion is mainly done by using JavaScript’s built-in functions;

  • Implicit type conversion means JavaScript automatically converts according to the computing environment The type of value.

In js, if you want to convert an object into a primitive value, you must call the toPrimitive() internal function, so how does it work?

toPrimitive(input,preferredType)

input is the input value, preferredType is the type expected to be converted, it can be String or Number, or not passed.

1) If the converted type is number, the following steps will be performed:

 1. 如果input是原始值,直接返回这个值;

 2. 否则,如果input是对象,调用input.valueOf(),如果结果是原始值,返回结果;

 3. 否则,调用input.toString()。如果结果是原始值,返回结果;

 4. 否则,抛出错误。

2) If the converted type is String, 2 and 3 will be executed interchangeably, that is, toString will be executed first. ()method.

3) You can omit preferredType. At this time, the date will be considered as a string, and other values ​​will be treated as Number.

① If the input is the built-in Date type, the preferredType is regarded as String

② Otherwise, it is regarded as Number, first call valueOf, and then call toString

ToBoolean( argument)

Type Return result
Underfined false
Null false
Boolean argument
Number Only when argument is 0, -0 or NaN, return false; otherwise return true
String Only when argument is an empty string ( When the length is 0), return false; otherwise return true
Symbol true
Object true

Note: Except underfined,null,false,NaN,'',0,-0, all others return true

ToNumber(argument)

##Object**First primValue= toPrimitive(argument,number), then use ToNumber(primValue)**# for primValue ##ToString(argument)
Type Return result
Underfined NaN
Null 0
Boolean argument is true, return 1; is false, return 0
Number argument
String replace the content in the string Convert to a number, such as '23'=>23; If the conversion fails, return NaN, such as '23a'=>NaN
Symbol throw TypeError exception

##TypeReturn resultUnderfined"underfined"Null"null"BooleanIf the argument is true, return "true"; if it is false, return "false"NumberUse a string to represent this numberStringargumentSymbolThrows TypeError exception Object**First primValue= toPrimitive(argument,string), then use ToString(primValue) for primValue**
##

1.隐式类型转换:

1.1-隐式转换介绍

· 在js中,当运算符在运算时,如果两边数据不统一,CPU就无法计算,这时我们编译器会自动将运算符两边的数据做一个数据类型转换,转成一样的数据类型再计算

这种无需程序员手动转换,而由编译器自动转换的方式就称为隐式转换

· 例如1 > "0"这行代码在js中并不会报错,编译器在运算符时会先把右边的"0"转成数字0`然后在比较大小
————————————————
1.2-隐式转换规则

(1). 转成string类型: +(字符串连接符)
(2).转成number类型:++/–(自增自减运算符) + - * / %(算术运算符) > =

加法规则
1.令lval=符号左边的值,rval=符号右边的值
2.令lprim=toPrimitive(lval),rprim=toPrimitive(rval)
如果lprim和rprim中有任意一个为string类型,将ToString(lprim)和ToString(rprim)的结果做字符串拼接
否则,将ToNumber(lprim)和ToNumber(rprim)的结果做算数加法

双等规则
1.xy都为Null或者underfined,return true;一方为Null或者underfined、NaN,return false
2.如果x和y为String,Number,Boolean并且类型不一致,都转为Number在进行比较
3.如果存在Object,转换为原始值在进行比较

   //特殊情况,xy都为Null或者underfined,return true
 console.log(undefined==undefined) //true
 console.log(undefined==null) //true
 console.log(null==null) //true
 //一方为Null或者underfined、NaN,return false
 console.log("0"==null) //false
 console.log("0"==undefined) //false
 console.log("0"==NaN) //false
 console.log(false==null) //false
 console.log(false==undefined) //false
 console.log(false==NaN) //false
  
 console.log("0"=="") //false
 console.log("0"==0) //true
 console.log(""==[]) //true
 console.log(false==0) //true
 console.log(false==[]) //true

(3). 转成boolean类型:!(逻辑非运算符)

  //1.字符串连接符与算术运算符隐式转换规则易混淆
  console.log(1+true)        // 1+Number(true) ==> 1+1=2
  //xy有一边为string时,会做字符串拼接
  console.log(1+'true')     //String(1)+2 ==> '1true'
  console.log('a'+ +'b')     //aNaN
  console.log(1+undefined)  //1+Number(undefined)==>1+NaN=NaN
  console.log(null+1)       //Number(null)+1==>0+1=1
 //2.会把其他数据类型转换成number之后再比较关系
  //注意:左右两边都是字符串时,是要按照字符对应的unicode编码转成数字。查看字符串unicode的方法:字符串.charCodeAt(字符串下标,默认为0)
 console.log('2'>'10')        //'2'.charCodeAt()>'10'.charCodeAt()=50>49==>true  

  //特殊情况,NaN与任何数据比较都是NaN
 console.log(NaN==NaN)        //false
 //3.复杂数据类型在隐式转换时,原始值(valueOf())不是number,会先转成String,然后再转成Number运算
  console.log(false=={})    //false   //({}).valueOf().toString()="[object Object]"
  console.log([]+[])        //""       //[].valueOf().toString()+[].valueOf().toString()=""+""=""
  console.log({}+[])         //0
  console.log(({})+[])      //"[object Object]"
  console.log(5/[1])         //5
  console.log(5/null)         //5
  console.log(5+{toString:function(){return 'def'}})         //5def
  console.log(5+{toString:function(){return 'def'},valueOf:function(){return 3}})         //5+3=8
 //4.逻辑非隐式转换与关系运算符隐式转换搞混淆(逻辑非,将其他类型转成boolean类型)
 console.log([]==0)   //true
 console.log({}==0)   //false
 console.log(![]==0)   //true
 console.log([]==![])   //true
 console.log([]==[])   //false     //坑
 console.log({}=={})   //false     //坑
 console.log({}==!{})   //false    //坑

2.强制类型(显式类型)转换:

通过手动进行类型转换,Javascript提供了以下转型函数:

转换为数值类型:Number(mix)、parseInt(string,radix)、parseFloat(string)
转换为字符串类型:toString(radix)、String(mix)
转换为布尔类型:Boolean(mix)

2.1 Boolean(value)、Number(value) 、String(value)

new Number(value) 、new String(value)、 new Boolean(value)传入各自对应的原始类型的值,可以实现“装箱”-----即将原始类型封装成一个对象。其实这三个函数不仅可以当作构造函数,还可以当作普通函数来使用,将任何类型的参数转化成原始类型的值。

其实这三个函数在类型转换的时候,调用的就是js内部的ToBoolean(argument)、ToNumber(argument)、ToString(argument)
2.2 parseInt(string,radix)
将字符串转换为整数类型的数值。它也有一定的规则:

(1)忽略字符串前面的空格,直至找到第一个非空字符
(2)如果第一个字符不是数字符号或者负号,返回NaN
(3)如果第一个字符是数字,则继续解析直至字符串解析完毕或者遇到一个非数字符号为止
(4)如果上步解析的结果以0开头,则将其当作八进制来解析;如果以0x开头,则将其当作十六进制来解析
(5)如果指定radix参数,则以radix为基数进行解析

   let objj={
       valueOf:function(){return '2px'},
       toString:function(){return []}
    }
    parseInt(objj)   //2
    parseInt('001')  //1   
    parseInt('22.5')  //22
    parseInt('123sws')  //123   
    parseInt('sws123')  //NaN
    //特殊的
    parseInt(function(){},16)   //15
    parseInt(1/0,19)               //18
    //浏览器代码解析器:parseInt里面有两个参数,第二个参数是十九进制(0,1,2,3,4,5,6,7,8,9,a,b,c,d,e,f,g,h,i),额,1/0,好吧先运算 结果等于Infinity,
   //I好的十九进制有认识,n十九进制不存在不认识,不管后面有没有了,立即返回i(i对应的十进制中的18),所以返回18
    parseInt(1/0,16)                //NaN   //同上,16进制灭有对应i,返回NaN
    parseInt(0.0000008)         //8    //String(0.0000008),结果为8e-7
    parseInt(0.000008)        //0
    parseInt(false,16)         //250   //16进制,'f'认识, 'a'认识, 'l'哦,不认识,立即返回fa (十六进制的fa转换成十进制等于250)
    parseInt('0x10'))          //16     //只有一个参数,好的,采用默认的十进制, '0x',额,这个我认识,是十六进制的写法, 十六进制的10转换成十进制等于16
    parseInt('10',2)              //2     //返回二进制的10 转换成十进制等于2

2.3 parseFloat(string)

将字符串转换为浮点数类型的数值.规则:

它的规则与parseInt基本相同,但也有点区别:字符串中第一个小数点符号是有效的,另外parseFloat会忽略所有前导0,如果字符串包含一个可解析为整数的数,则返回整数值而不是浮点数值。

2.4 toString(radix)

除undefined和null之外的所有类型的值都具有toString()方法,其作用是返回对象的字符串表示

【相关推荐:javascript学习教程

The above is the detailed content of What are the two types of data type conversion in JavaScript?. 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
React Inside HTML: Integrating JavaScript for Dynamic Web PagesReact Inside HTML: Integrating JavaScript for Dynamic Web PagesApr 16, 2025 am 12:06 AM

To integrate React into HTML, follow these steps: 1. Introduce React and ReactDOM in HTML files. 2. Define a React component. 3. Render the component into HTML elements using ReactDOM. Through these steps, static HTML pages can be transformed into dynamic, interactive experiences.

The Benefits of React: Performance, Reusability, and MoreThe Benefits of React: Performance, Reusability, and MoreApr 15, 2025 am 12:05 AM

React’s popularity includes its performance optimization, component reuse and a rich ecosystem. 1. Performance optimization achieves efficient updates through virtual DOM and diffing mechanisms. 2. Component Reuse Reduces duplicate code by reusable components. 3. Rich ecosystem and one-way data flow enhance the development experience.

React: Creating Dynamic and Interactive User InterfacesReact: Creating Dynamic and Interactive User InterfacesApr 14, 2025 am 12:08 AM

React is the tool of choice for building dynamic and interactive user interfaces. 1) Componentization and JSX make UI splitting and reusing simple. 2) State management is implemented through the useState hook to trigger UI updates. 3) The event processing mechanism responds to user interaction and improves user experience.

React vs. Backend Frameworks: A ComparisonReact vs. Backend Frameworks: A ComparisonApr 13, 2025 am 12:06 AM

React is a front-end framework for building user interfaces; a back-end framework is used to build server-side applications. React provides componentized and efficient UI updates, and the backend framework provides a complete backend service solution. When choosing a technology stack, project requirements, team skills, and scalability should be considered.

HTML and React: The Relationship Between Markup and ComponentsHTML and React: The Relationship Between Markup and ComponentsApr 12, 2025 am 12:03 AM

The relationship between HTML and React is the core of front-end development, and they jointly build the user interface of modern web applications. 1) HTML defines the content structure and semantics, and React builds a dynamic interface through componentization. 2) React components use JSX syntax to embed HTML to achieve intelligent rendering. 3) Component life cycle manages HTML rendering and updates dynamically according to state and attributes. 4) Use components to optimize HTML structure and improve maintainability. 5) Performance optimization includes avoiding unnecessary rendering, using key attributes, and keeping the component single responsibility.

React and the Frontend: Building Interactive ExperiencesReact and the Frontend: Building Interactive ExperiencesApr 11, 2025 am 12:02 AM

React is the preferred tool for building interactive front-end experiences. 1) React simplifies UI development through componentization and virtual DOM. 2) Components are divided into function components and class components. Function components are simpler and class components provide more life cycle methods. 3) The working principle of React relies on virtual DOM and reconciliation algorithm to improve performance. 4) State management uses useState or this.state, and life cycle methods such as componentDidMount are used for specific logic. 5) Basic usage includes creating components and managing state, and advanced usage involves custom hooks and performance optimization. 6) Common errors include improper status updates and performance issues, debugging skills include using ReactDevTools and Excellent

React and the Frontend Stack: The Tools and TechnologiesReact and the Frontend Stack: The Tools and TechnologiesApr 10, 2025 am 09:34 AM

React is a JavaScript library for building user interfaces, with its core components and state management. 1) Simplify UI development through componentization and state management. 2) The working principle includes reconciliation and rendering, and optimization can be implemented through React.memo and useMemo. 3) The basic usage is to create and render components, and the advanced usage includes using Hooks and ContextAPI. 4) Common errors such as improper status update, you can use ReactDevTools to debug. 5) Performance optimization includes using React.memo, virtualization lists and CodeSplitting, and keeping code readable and maintainable is best practice.

React's Role in HTML: Enhancing User ExperienceReact's Role in HTML: Enhancing User ExperienceApr 09, 2025 am 12:11 AM

React combines JSX and HTML to improve user experience. 1) JSX embeds HTML to make development more intuitive. 2) The virtual DOM mechanism optimizes performance and reduces DOM operations. 3) Component-based management UI to improve maintainability. 4) State management and event processing enhance interactivity.

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

mPDF

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

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

MinGW - Minimalist GNU for Windows

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.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft