JavaScript data type conversion principles
JavaScript is a weakly typed (or dynamically typed) language, that is, the type of variables is undefined. The following article will share with you a summary of JavaScript data type conversion, including explicitly converted data types and implicit data type conversions. Friends who are interested should take a look.
We all know that JavaScript is a weak type ( (or dynamically typed) language, that is, the type of the variable is undefined.
var num = 123 ; //123 var num = 'HAHAHA' + num ; // "HAHAHA123"
In the above code, the variable num is a numerical value at first, and then becomes a string. The variable type is determined entirely by the current value. This type is called a weak type.
We know that in programming languages, there are types between the data itself and operations.
In a strongly typed programming language, variables of different types cannot be directly operated.
However, in weakly typed languages, variables of different types can be added directly, so the data type needs to be converted during the operation. This data type conversion is automatic in most cases, but sometimes it requires manual conversion.
Before performing data type conversion, let's first understand what the data types of JavaScript are.
#5 basic data types: number, string, boolean, undefined, unll.
A complex data type: Object .
# Sometimes when we need to know the data type of a variable, we can operate it through typeof(). The return value type is: string.
<script> var arr = [undefined , true , 'world' , 123 , null , new Object , function () {}] for ( i = 0; i < arr.length; i ++) { console.log(typeof(arr[i])); } </script>
The output results are: undefined, boolean, string, number, object, object, function
null is obviously a basic data type. , why the output result is Object. This is because null is considered an empty object reference. Just remember.
The function is not a data type, but why does the function type appear after calling typeof? From a technical perspective, functions are objects. But there are also some special attributes, so it is necessary to use typeof to distinguish functions and objects.
Explicitly converted data types
1. Function that converts non-numeric values to numeric types
There are three functions that can convert non-numeric values into numeric values: Number(), parseInt(), and parseFloat().
The first function Number(mix) can be used for any data type. This function first converts the data type of mix to number type, and then converts the value of mix to numeric value.
If the value of mix can be directly converted into a number, it will be displayed directly. If not, 0 or NaN is displayed.
The other two functions are specifically used to convert strings into numerical values.
parseInt(string) function: Convert a string to a numerical value without rounding. The string here must be the starting string of numeric type, and the traversal will not stop until the non-numeric character. If it does not start with a number, NaN.
<script> var num = ["123" , "124.4" , "234asd" , "asf456"] ; for (i = 0; i < num.length; i++) { console.log(parseInt(num[i])); } </script>
will be displayed. The execution results are: 123, 124, 234, NaN.
parseFloat(string): Convert string to floating point number. Starting from the numeric digit and ending with the non-numeric digit, the usage is consistent with parseInt(string).
The parseInt() function has another usage. parseInt(string,radix):
Using radix as the base, convert the string into a decimal integer. The value of radix is 2-32.
2. Functions that convert other types of data into string types
There are two functions that can convert other data types into strings. toString() and string() .
String(mix): Convert mix to string type. This function can convert a value of any data type into a string.
The toString() function has two uses. ,
Usage 1: demo.toString(): Convert demo to string type. demo cannot be equal to null undefined
Usage 2: demo.toString(radix): Convert the decimal number demo to the target number. For example, 123.0.toString(8) converts the decimal number 123 into an octal string.
Note: It cannot be written as 123.toString(8). Because the browser will parse it into a decimal when parsing.
//Example question: Convert a binary number 10001000 into a hexadecimal number.
//Idea: First convert binary to decimal, and then convert from decimal to hexadecimal.
var num1 = parseInt('10001000',2); //136 var num2 = num1.toString(16); //'88'
3. Convert the value to a Boolean value type
Boolean (variable): Convert a Values are converted to their corresponding Boolean values.
(1) Conversion method for primitive type values
The conversion results of the following six values are false, and all other values are true.
undefined
null
- ##-0
- 0
- NaN
- '' (empty string)
Boolean(new Boolean(false)) // true
Boolean([]); // true Boolean({}); // true
隐式的数据类型转换
隐式类型的转换是系统进行运算时自动进行的,但是调用的方法都是显式类型转换的方法。
1、递增和递减操作符
a++ ,a-- ,++a , --a
这4个操作符对任何值都适用,也就是他们不仅适用于整数,还可以用于字符串、布尔值、浮点数值和对象,此时伴随着隐式的数据类型转换。
即先将变量通过Number()转换成number的数据类型,然后再进行递增、递减操作。
2、(+)(-),即正负号
不仅适用于整数,还可以用于字符串、布尔值、浮点数值和对象。将变量通过Number()转换成number的数据类型。
3、isNaN(变量)
执行过程为:即先将变量通过Number转换,再进行isNaN() 。
4、(+) 加号
先看下面的一段代码
<script> var str = 1 + "1"; var num = 1 + 1; var num1 = 1 + false; document.write(str , "<br>" , num , "<br>" , num1); </script>
执行结果为:11 , 2 ,1
所以加法有两个作用。如果没有运算过程中没有字符串时,就将变量通过Number()转换为number类型后,再进行运算。如果有字符串的话,加号两边起的就是字符串连接作用。
5、- * / % 减号,乘号,除号,取余
运算时把数据转换成number类型后,再进行运算。
6、&& || ! 与或非运算
将运算符两边的值转换成通过Boolean()函数转换成布尔类型,然后再进行运算。不同的是,&& || 返回的是比较后自身的原值,而 !运算返回的是布尔值.
看一个例子。
<script> console.log(5 && 3); //从左往右判断,如果全都为真,则返回最后一个为真的值,只要有一个判断为假,就返回为假的那个值 console.log(0 || 2); //从左往右判断,返回第一个为真的值,若完成了全部的判断且所有的值都为假,就返回最后为假的那个值 console.log(!3); </script>
返回的结果为:3 , 2 , false.
7、 < > <= >= == != 比较运算符
当数字和字符串比较大小时,会隐示将字符串转换成number类型进行比较。而当字符串和字符串比较大小时,则比较的是ascii码的大小。最后返回的则是布尔值
<script> //1)纯数字之间比较 alert(1<3);//true //2)数字字符串比较,会将其先转成数字 alert("1"<"3");//true alert("123"<"123");//false //3)纯字符串比较,先转成ascii码 alert("a"<"b");//true alert("abc"<"aad");//false,多纯字母比较,会依次比较ascii码 //4)汉字比较 alert("我".charCodeAt());//25105 alert("的".charCodeAt());//30340 alert("我"<"的");//true,汉字比较,转成ascii码 //5)当数字和字符串比较,且字符串为数字。则将数字字符串转为数字 alert(123<"124");//true,下面一句代码得出124的ascii码为49,所以并不是转成 ascii比较 alert("124".charCodeAt());//49 //6)当数字和字符串比较,且字符串为非纯数字时,则将非数字字符串转成数字的时候会转换为NaN,当NaN和数字比较时不论大小都返回false. alert(13>"abc");//false </script>
下面看一种特殊情况。
<script> //undefined不发生类型转换 console.log(undefined == undefined); //true console.log(undefined == 0); //false console.log(undefined > 0); //false console.log(undefined < 0); //false //null不发生类型转换 console.log(null == null); //true console.log(null == 0); //false console.log(null > 0); //false console.log(null < 0); //false console.log(undefined == null); //true console.log(NaN == NaN); //false. not a number 不等于任何东西,包括它自己 </script>
关于 == 的隐式类型转换,可以看博客:http://www.jb51.net/article/136521.htm
在项目工程中,如果用 == 来判断两个数值是否相等,由于会发生隐式类型转换。所以是非常存在非常大的漏洞的。为了解决这一问题。引入了 === (绝对等于)和 !==(绝对不等于)。
<script> console.log(1 === "1"); //false console.log(1 === 1); //true </script>
上面是我整理给大家的,希望今后会对大家有帮助。
相关文章:
The above is the detailed content of JavaScript data type conversion principles. For more information, please follow other related articles on the PHP Chinese website!

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

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

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest
