Table of Contents
Forced type conversion
Convert to numeric type
Number(mix) function
parseInt(string, radix) function
parseFloat(string) function
Convert to string type
Convert to Boolean type
Home Web Front-end JS Tutorial What are the three types of casts in JavaScript?

What are the three types of casts in JavaScript?

Jul 16, 2021 pm 02:29 PM
javascript

The three forced type conversions are: 1. Conversion to numeric type, Number(), parseInt(), parseFloat(); 2. Conversion to string type, toString(), String(); 3. Convert to Boolean type, Boolean().

What are the three types of casts in JavaScript?

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

JavaScript is a weakly typed language, and its value data type can be changed.

Some languages ​​require specifying the data type of each variable. Such a language is called a strongly typed language, such as java C

Forced type conversion

There are two types of type conversion: one One is explicit conversion, which requires programmers to manually write code conversion; the other is implicit conversion, which is converted by the JavaScript interpreter.

JavaScript provides the following functions for explicit conversion:

1. Convert to numeric type: Number(mix), parseInt(string,radix), parseFloat(string)

2. Convert to string type: toString(radix), String(mix)

3. Convert to Boolean type: Boolean(mix)

Convert to numeric type

Number(mix) function

Number(mix) function can convert any type of parameter mix into a numerical type. The rules are:

1. If it is a Boolean value, true and false are converted to 1 and 0 respectively

2. If it is a numeric value, it returns itself.

3. If it is null, return 0

4. If it is undefined, return NaN.

5. If it is a string, follow the following rules:

a. If the string only contains numbers, convert it to decimal (ignoring the leading 0)

b. If the string contains a valid floating point format, convert it to a floating point value (ignoring the leading 0)

c. If it is an empty string, convert it to 0

d. If the string contains a format other than the above, convert it to NaN

6. If it is an object, call the valueOf() method of the object, and then convert the returned value according to the previous rules. If the result of the conversion is NaN, call the object's toString() method and convert the returned string value again according to the previous rules.

Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>数据类型转换</title>
</head>
<body>
<script>

    println(Number(false));
    println(Number(true));
    println(Number(123));
    println(Number(null));
    println(Number(undefined));
    println(Number(person));


    function println(a){
        document.write(a+&#39;<br>&#39;);
    }

    var person={};//字面量创建对象

    // 设置字面量对象属性
    person.name=&#39;huangshiren&#39;;
    person.age=58;
    person.appetite=3;
    person.eat=function(){
        document.write(&#39;正在吃饭&#39;);
    }
</script>
</body>
</html>
Copy after login

parseInt(string, radix) function

Parameter description:

string The value to be parsed. If the argument is not a string, it is converted to a string (using the ToString abstract operation). Whitespace characters at the beginning of the string will be ignored.

radix An integer between 2 and 36 (the basis of mathematical systems) that represents the radix of the above string. For example, the parameter "10" means using the decimal numerical system we usually use. Always specifying this parameter eliminates confusion when reading this code and ensures that the conversion results are predictable. Different implementations produce different results when the base is not specified, usually defaulting to 10.

parseInt(string, radix) function converts a string into an integer type value. It also has certain rules:

1. Ignore spaces in front of the string until the first non-empty character is found

2. If the first character is not a numeric sign or a negative sign, return NaN

3. If the first character is a number, continue parsing until the string is parsed or a non-numeric symbol is encountered.

4. If the result of the previous step starts with 0 , it will be parsed as octal; if it starts with x, it will be parsed as hexadecimal

5. If the radix parameter is specified, radix will be used as the base for parsing

Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>数据类型转换</title>
</head>
<body>
<script>

    println(parseInt("12.34567",10));
    println(parseInt("de",10));
    println(parseInt("0123456789",10));
    println(parseInt("0e0",16));
    println(parseInt("0101010001",2));

    function println(a){
        document.write(a+&#39;<br>&#39;);
    }


</script>
</body>
</html>
Copy after login

parseFloat(string) function

parseFloat(string) function converts a string into a floating point type value.

Its rules are basically the same as parseInt, but there are some differences: the first decimal point symbol in the string is valid, and parseFloat will ignore all leading 0s. If the string contains a number that can be parsed as an integer , returns an integer value instead of a floating point value.

Example

 <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>数据类型转换</title>
</head>
<body>
<script>

    println(parseFloat("3.14"));
    println(parseFloat("314e-2"));
    println(parseFloat("0.0314E+2"));
    println(parseFloat("3.14more non-digit characters"));

    function println(a){
        document.write(a+&#39;<br>&#39;);
    }


</script>
</body>
</html>
Copy after login

Convert to string type

toString(radix) method. All types of values ​​except undefined and null have a toString() method, which returns a string representation of the object.

Example

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>数据类型转换</title>
</head>
<body>
<script>

    var count=10;
    println(count.toString());

    var boolean=true;
    println(boolean.toString());

    var today=new Date();
    println(today.toString());

    var shoppingCart=[&#39;鞋&#39;,&#39;连衣裙&#39;,&#39;皮带&#39;];
    println(shoppingCart.toString());


    var person={};//字面量创建对象

    // 设置字面量对象属性
    person.name=&#39;huangshiren&#39;;
    person.age=58;
    person.appetite=3;
    person.eat=function(){
        document.write(&#39;正在吃饭&#39;);
    }

    println(person.toString());


    function println(a){
        document.write(a+&#39;<br>&#39;);
    }


</script>
</body>
</html>
Copy after login

Convert to Boolean type

Boolean(mix) function converts any type of value to a Boolean value.

Example

 <!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>数据类型转换</title>
</head>
<body>
<script>

    var count=10;

    println(Boolean(count));
    println(Boolean(0));
    println(Boolean(4<3));
    println(Boolean(null));
    println(Boolean(""));
    println(Boolean(undefined));

    var shoppingCart=[&#39;鞋&#39;,&#39;连衣裙&#39;,&#39;皮带&#39;];
    println(Boolean(shoppingCart));



    var person={};//字面量创建对象

    // 设置字面量对象属性
    person.name=&#39;huangshiren&#39;;
    person.age=58;
    person.appetite=3;
    person.eat=function(){
        document.write(&#39;正在吃饭&#39;);
    }

    println(Boolean(person));

    function println(a){
        document.write(a+&#39;<br>&#39;);
    }


</script>
</body>
</html>
Copy after login

[Recommended learning: javascript advanced tutorial]

The above is the detailed content of What are the three types of casts in JavaScript?. 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

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 ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

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.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

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

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

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

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

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

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

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

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles