Home Web Front-end JS Tutorial How to convert JS data types

How to convert JS data types

Mar 17, 2018 am 09:30 AM
javascript how Convert

This time I will bring you JSData typeHow to convert, what are the precautions for converting JS data type, the following is a practical case, let's take a look.

We all know that JavaScript is a weakly typed (or dynamically typed) language, that is, the type of variables is uncertain.

var num = 123 ; //123
var num = 'HAHAHA' + num ; // "HAHAHA123"
Copy after login

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 forced conversion.

Before performing data type conversion, let’s first understand JavaScript What are the data types of .

  • #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>
Copy after login

The output results are: undefined, boolean, string, number, object, object, function

null is obviously a basic data type, why is the output result Object. This is because null An object reference is considered null. 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 will be displayed.

<script>
var num = ["123" , "124.4" , "234asd" , "asf456"] ;
  for (i = 0; i < num.length; i++) {
   console.log(parseInt(num[i]));
  }
</script>
Copy after login

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 string types. 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 into 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'
Copy after login

3、将值转换成布尔值类型

Boolean(变量):将一个值转换成其对应的布尔值。

(1)原始类型值的转换方法

以下六个值的转化结果为false,其他的值全部为true。

  • undefined

  • null

  • -0

  • +0

  • NaN

  • ''(空字符串)

(2)对象的转换规则

所有对象的布尔值都是true,甚至连false对应的布尔对象也是true。

Boolean(new Boolean(false))
// true
Copy after login

请注意,空对象{}和空数组[]也会被转成true。

Boolean([]); // true
Boolean({}); // true
Copy after login

隐式的数据类型转换

隐式类型的转换是系统进行运算时自动进行的,但是调用的方法都是显式类型转换的方法。

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>
Copy after login

执行结果为:11 , 2 ,1

所以加法有两个作用。如果没有运算过程中没有字符串时,就将变量通过Number()转换为number类型后,再进行运算。如果有字符串的话,加号两边起的就是字符串连接作用。

5、-  *  /  %  减号,乘号,除号,取余 

运算时把数据转换成number类型后,再进行运算。

6、&&  ||  !    与或非运算 

将运算符两边的值转换成通过Boolean()函数转换成布尔类型,然后再进行运算。不同的是,&&  ||  返回的是比较后自身的原值,而 !运算返回的是布尔值.

看一个例子。

<script>
  console.log(5 && 3);  //从左往右判断,如果全都为真,则返回最后一个为真的值,只要有一个判断为假,就返回为假的那个值
  console.log(0 || 2);  //从左往右判断,返回第一个为真的值,若完成了全部的判断且所有的值都为假,就返回最后为假的那个值
   console.log(!3);
 </script>
Copy after login

返回的结果为: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>
Copy after login

  下面看一种特殊情况。

<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>
Copy after login

  关于 == 的隐式类型转换,可以看博客:http://www.jb51.net/article/136521.htm

在项目工程中,如果用 == 来判断两个数值是否相等,由于会发生隐式类型转换。所以是非常存在非常大的漏洞的。为了解决这一问题。引入了 === (绝对等于)和 !==(绝对不等于)。

<script>
 console.log(1 === "1"); //false
 console.log(1 === 1);   //true
</script>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

简单高效的JSON

在angular中$http服务需要如何使用

What are the three attributes of a javascript object

How to use angular’s ​​custom instructions

The above is the detailed content of How to convert JS data types. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
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

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

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Practical tips for converting full-width English letters into half-width form Practical tips for converting full-width English letters into half-width form Mar 26, 2024 am 09:54 AM

Practical tips for converting full-width English letters into half-width forms. In modern life, we often come into contact with English letters, and we often need to input English letters when using computers, mobile phones and other devices. However, sometimes we encounter full-width English letters, and we need to use the half-width form. So, how to convert full-width English letters to half-width form? Here are some practical tips for you. First of all, full-width English letters and numbers refer to characters that occupy a full-width position in the input method, while half-width English letters and numbers occupy a full-width position.

How to convert AI files to CDR format How to convert AI files to CDR format Feb 19, 2024 pm 04:09 PM

AI files refer to vector graphics files created by Adobe Illustrator (AI for short) software, while CDR files refer to vector graphics files created by CorelDRAW software. Since these two softwares are developed by different manufacturers, their file formats are different and cannot be directly converted to each other. However, we can convert AI files to CDR files through some methods. A commonly used conversion method will be introduced below. Step 1: Export AI files to EPS format AdobeIllust

How to convert ODT to Word in Windows 11/10? How to convert ODT to Word in Windows 11/10? Feb 20, 2024 pm 12:21 PM

In this article, we will show you how to convert OpenDocumentTextDocument (ODT) files to Microsoft Word (Docx, DOC, etc.). Format. How to Convert ODT to Word in Windows 11/10 Here is how you can convert ODT documents to DOC or DOCX format on Windows PC: Convert ODT to Word using WordPad or Word The first method we are going to show you Is to use WordPad or MicrosoftWord to convert ODT to Word. Here are the steps to achieve this: First, open the WordPad app using the Start menu. Now, go to

How to convert a virtual machine to a physical machine? How to convert a virtual machine to a physical machine? Feb 19, 2024 am 11:40 AM

Converting a virtual machine (VM) to a physical machine is the process of migrating a virtual instance and associated application software to a physical hardware platform. This conversion helps optimize operating system performance and hardware resource utilization. This article aims to provide an in-depth look at how to make this conversion. How to implement migration from virtual machine to physical machine? Typically, the conversion process between a virtual machine and a physical machine is performed outside the virtual machine by third-party software. This process consists of multiple stages involving the configuration of virtual machines and the transfer of resources. Prepare the physical machine: The first step is to ensure that the physical machine meets the hardware requirements for Windows. We need to back up the data on a physical machine as the conversion process will overwrite the existing data. *Username and password for an administrator account with administrator rights to create system images. will be virtual

Golang time processing: How to convert timestamp to string in Golang Golang time processing: How to convert timestamp to string in Golang Feb 24, 2024 pm 10:42 PM

Golang time conversion: How to convert timestamp to string In Golang, time operation is one of the very common operations. Sometimes we need to convert the timestamp into a string for easy display or storage. This article will introduce how to use Golang to convert timestamps to strings and provide specific code examples. 1. Conversion of timestamps and strings In Golang, timestamps are usually expressed in the form of integer numbers, which represent the number of seconds from January 1, 1970 to the current time. The string is

Detailed explanation of the implementation method of converting PHP months to English months Detailed explanation of the implementation method of converting PHP months to English months Mar 21, 2024 pm 06:45 PM

This article will introduce in detail how to convert months in PHP to English months, and give specific code examples. In PHP development, sometimes we need to convert digital months to English months, which is very practical in some date processing or data display scenarios. The implementation principles, specific code examples and precautions will be explained in detail below. 1. Implementation principle In PHP, you can convert digital months into English months by using the DateTime class and format method. Date

How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone How to convert qq music to mp3 format Convert qq music to mp3 format on mobile phone Mar 21, 2024 pm 01:21 PM

QQ Music allows everyone to enjoy watching movies and relieve boredom. You can use this software every day to easily satisfy your needs. A large number of high-quality songs are available for everyone to listen to. You can also download and save them. The next time you listen to them, you don’t need an Internet connection. The songs downloaded here are not in MP3 format and cannot be used on other platforms. After the membership songs expire, there is no way to listen to them again. Therefore, many friends want to convert the songs into MP3 format. Here, the editor explains You provide methods so that everyone can use them! 1. Open QQ Music on your computer, click the [Main Menu] button in the upper right corner, click [Audio Transcoding], select the [Add Song] option, and add the songs that need to be converted; 2. After adding the songs, click to select Convert to [mp3]

How to convert full-width English letters into half-width letters How to convert full-width English letters into half-width letters Mar 25, 2024 pm 02:45 PM

How to convert full-width English letters into half-width letters In daily life and work, sometimes we encounter situations where we need to convert full-width English letters into half-width letters, such as when entering computer passwords, editing documents, or designing layouts. Full-width English letters and numbers refer to characters with the same width as Chinese characters, while half-width English letters refer to characters with a narrower width. In actual operation, we need to master some simple methods to convert full-width English letters into half-width letters so that we can process text and numbers more conveniently. 1. Full-width English letters and half-width English letters

See all articles