search
HomeWeb Front-endJS TutorialCommon functions and codes for js variable type conversion [comprehensive]_javascript skills

1. Conversion function:

js provides two conversion functions, parseInt() and parseFloat(). The former converts the value into an integer, and the latter converts the value into a floating point number. Only by calling these methods on the String type can these two functions run correctly; for other types, NaN (Not a Number) is returned.

Both parseInt() and parseFloat() will carefully analyze the string before determining whether it is a numeric value. The parseInt() method first checks the character at position 0 to determine whether it is a valid number; if not, the method will return NaN and will not continue to perform other operations. But if the character is a valid number, the method will look at the character at position 1 and perform the same test. This process will continue until a character that is not a valid number is found, at which time parseInt() will convert the string before the character into a number.

For example, if you want to convert the string "1234blue " into an integer, then parseInt() will return 1234 because when it detects the character b, it will stop the detection process. Numeric literals contained in strings are correctly converted to numbers, so the string "0xA" is correctly converted to the number 10. However, the string "22.5" will be converted to 22 because the decimal point is an invalid character for integers. Some examples are as follows:

parseInt("1234blue"); //returns 1234
parseInt("0xA"); //returns 10
parseInt("22.5"); //returns 22
parseInt("blue"); //returns NaN

The parseInt() method also has a base mode, which can convert binary, octal, hexadecimal or any other base string into an integer. The base is specified by the second parameter of the parseInt() method, so to parse the hexadecimal value, you need to call the parseInt() method as follows:
parseInt("AF", 16); //returns 175
Of course, for binary, octal, or even decimal (default mode), you can call the parseInt() method like this:
parseInt("10", 2); //returns 2
parseInt("10", 8); //returns 8
parseInt("10", 10); //returns 10
If the decimal number contains leading 0s, it is best to use base 10 so that you do not accidentally get an octal value . For example:
parseInt("010"); //returns 8
parseInt("010", 8); //returns 8
parseInt("010", 10); //returns 10
In this code, both lines of code parse the string "010" into a number. The first line of code treats this string as an octal value and parses it in the same way as the second line of code (which declares base 8). The last line of code declares base 10, so iNum3 ends up equaling 10.

The parseFloat() method is similar to the parseInt() method. It looks at each character starting from position 0 until the first non-valid character is found, and then converts the string before the character into number. However, for this method, the first decimal point is a valid character. If there are two decimal points, the second decimal point will be considered invalid, and the parseFloat() method will convert the string before this decimal point into a number. This means that the string "22.34.5" will be parsed as 22.34.
Another difference in using the parseFloat() method is that the string must represent the floating point number in decimal form, not in octal or hexadecimal form. The
method ignores leading 0s, so the octal number 0908 will be parsed as 908. For the hexadecimal number 0xA, the method will return NaN because x is not a valid character in floating point numbers. In addition, parseFloat() has no base mode.

The following is an example of using the parseFloat() method:
parseFloat("1234blue"); //returns 1234.0
parseFloat("0xA"); //returns NaN
parseFloat(" 22.5"); //returns 22.5
parseFloat("22.34.5"); //returns 22.34
parseFloat("0908"); //returns 908
parseFloat("blue"); // returns NaN

2. Forced type conversion

You can also use type casting to process the type of the converted value. Use a cast to access a specific value, even if it is of another type.
The three types of casts available in ECMAScript are as follows:
Boolean(value) - Convert the given value into Boolean type;
Number(value) - Convert the given value into a number (Can be an integer or floating point number);
String(value) - Convert the given value into a string.
Converting a value using one of these three functions will create a new value that stores the value directly converted from the original value. This can have unintended consequences.
The Boolean() function returns true when the value to be converted is a string, non-zero number, or object with at least one character (this will be discussed in the next section). If the value is an empty string, the number 0, undefined, or null, it will return false.

You can use the following code snippet to test Boolean type conversion.

Boolean(""); //false – empty string
Boolean("hi"); //true – non-empty string
Boolean(100); //true – non- zero number
Boolean(null); //false - null
Boolean(0); //false - zero
Boolean(new Object()); //true – object

Number()'s coercion is similar to the parseInt() and parseFloat() methods, except that it converts the entire value rather than part of the value.Remember, the parseInt() and parseFloat() methods only convert the string before the first invalid character, so "4.5.6" will be converted to "4.5". Casting with Number(), "4.5.6" will return NaN because the entire string value cannot be converted to a number. If the string value can be completely converted, Number() will determine whether to call the parseInt() method or the parseFloat() method. The following table illustrates what happens when the Number() method is called on different values:

Usage Result
Number(false) 0
Number(true) 1
Number(undefined) NaN
Number(null) 0
Number( "5.5 ") 5.5
Number( "56 ") 56
Number( "5.6.7 ") NaN
Number(new Object()) NaN
Number(100) 100

The last cast method, String(), is the simplest because it can convert any value into a string. To perform this cast, just call the toString() method on the value passed in as a parameter, which converts 1 to "1", true to "true", false to "false", and so on. analogy. The only difference between casting to a string and calling the toString() method is that casting a null or undefined value produces a string without raising an error:

var s1 = String(null); / /"null"
var oNull = null;
var s2 = oNull.toString(); //won't work, causes an error

3. Use js variable weak type conversion

Give me a small example, you will understand after you look at it.



The above example takes advantage of the weak type characteristics of js and only performs arithmetic operations to achieve type conversion from string to number. However, this method is not recommended. //Convert object to character

function object2String(obj) {
var val, output = "";
if (obj) {
output = "{ ";
for (var i in obj) {
val = obj[i];
switch (typeof val) {
case ("object"):
if (val[0 ]) {
output = i ":" array2String(val) ",";
} else {
output = i ":" object2String(val) ",";
}
break;
case ("string"):
output = i ":'" val "',";
break;
default:
output = i ":" val ", ";
}
}
output = output.substring(0, output.length-1) "}";
}
return output;
}
Convert array to string

function array2String(array) {
var output = "";
if (array) {
output = "[";
for (var i in array) {
val = array[i];
switch (typeof val) {
case ("object"):
if (val[0]) {
output = array2String(val) ",";
} else {
output = object2String(val) ",";
}
break;
case ("string"):
output = "'" encodeURI(val) "',";
break;
default:
output = val ",";
}
}
output = output .substring(0, output.length-1) "]";
}
return output;
}



function string2Object(string) {
eval("var result = " decodeURI(string));
return result;
}



function string2Array(string) {
eval("var result = " decodeURI(string));
return result;
}
Convert date type into string format in js
<script> <BR>var str= '012.345 '; <BR>var x = str-0; <BR>x = x*1; <BR></script>
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
JavaScript: Exploring the Versatility of a Web LanguageJavaScript: Exploring the Versatility of a Web LanguageApr 11, 2025 am 12:01 AM

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The Evolution of JavaScript: Current Trends and Future ProspectsThe Evolution of JavaScript: Current Trends and Future ProspectsApr 10, 2025 am 09:33 AM

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

Demystifying JavaScript: What It Does and Why It MattersDemystifying JavaScript: What It Does and Why It MattersApr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

Is Python or JavaScript better?Is Python or JavaScript better?Apr 06, 2025 am 12:14 AM

Python is more suitable for data science and machine learning, while JavaScript is more suitable for front-end and full-stack development. 1. Python is known for its concise syntax and rich library ecosystem, and is suitable for data analysis and web development. 2. JavaScript is the core of front-end development. Node.js supports server-side programming and is suitable for full-stack development.

How do I install JavaScript?How do I install JavaScript?Apr 05, 2025 am 12:16 AM

JavaScript does not require installation because it is already built into modern browsers. You just need a text editor and a browser to get started. 1) In the browser environment, run it by embedding the HTML file through tags. 2) In the Node.js environment, after downloading and installing Node.js, run the JavaScript file through the command line.

How to send notifications before a task starts in Quartz?How to send notifications before a task starts in Quartz?Apr 04, 2025 pm 09:24 PM

How to send task notifications in Quartz In advance When using the Quartz timer to schedule a task, the execution time of the task is set by the cron expression. Now...

In JavaScript, how to get parameters of a function on a prototype chain in a constructor?In JavaScript, how to get parameters of a function on a prototype chain in a constructor?Apr 04, 2025 pm 09:21 PM

How to obtain the parameters of functions on prototype chains in JavaScript In JavaScript programming, understanding and manipulating function parameters on prototype chains is a common and important task...

What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?What is the reason for the failure of Vue.js dynamic style displacement in the WeChat mini program webview?Apr 04, 2025 pm 09:18 PM

Analysis of the reason why the dynamic style displacement failure of using Vue.js in the WeChat applet web-view is using Vue.js...

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)
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Atom editor mac version download

Atom editor mac version download

The most popular open source editor