Home Web Front-end JS Tutorial Detailed explanation of js type conversion and reference types (Boolean_Number_String)_javascript skills

Detailed explanation of js type conversion and reference types (Boolean_Number_String)_javascript skills

May 16, 2016 pm 04:56 PM
js reference type type conversion

1. Type conversion

1. Convert to string
The interesting thing about ECMAScript’s Boolean values, numbers, and primitive values ​​of strings is that they are pseudo-objects, which means that they actually have properties and methods .
For example:

Copy code The code is as follows:

var sColor = "blue";
alert(sColor.length);//outputs "4"

In short, the three main primitive values ​​Boolean values, numbers and strings have toString() methods. All objects defined by ECMAScript have a toString() method, whether it is a pseudo object or a real object.

The Boolean toString() method just outputs "true" or "false", and the result is determined by the value of the variable:

Copy code The code is as follows:

var bFound = false;
alert(bFound.toString());//outputs "false"

Number type The toString() method is special. It has two modes, namely the default mode and the base mode. Using the default mode, the toString() method only uses the corresponding string to output a numeric value (whether it is an integer, floating point number or scientific notation) .
Copy code The code is as follows:

var iNum1 = 10;
var fNum2 = 10.0 ;
alert(iNum1.toString()); //outputs "10"
alert(fNum2.toString()); //outputs "10"

adopts Number type The base mode of the toString() method can output numbers in different bases (bases).
Copy code The code is as follows:

var iNum = 10;
alert(iNum. toString(2)); //outputs "1010"
alert(iNum.toString(8)); //outputs "12"
alert(iNum.toString(16)); //outputs "A"

2. Convert to numbers
ECMAScript provides two methods to convert non-numeric primitive values ​​into numbers, namely parseInt() and parseFloat().
Note: Only when these methods are called on the String type (except Number) can they run correctly. NaN will be returned for other types.

For example:

Copy code The code is as follows:

var iNum1 = parseInt("1234blue ");//returns 1234
var iNum2 = parseInt("oxA"); //returns 10
var iNum3 = parseInt("22.5"); //returns 22
var iNum4 = parseInt(" blue"); //returns NaN

The parseInt() method also has a base mode, which can convert binary, octal, hexadecimal or any other base string into a decimal integer. The second parameter specifies which base to parse.
Copy code The code is as follows:

var iNum1 = parseInt("AF",16); // returns 175
var iNum2 = parseInt("10",2); // returns 2
var iNum3 = parseInt("10",8); // returns 8
var iNum4 = parseInt( "10",10); //returns 10

Note: If the decimal number contains leading 0s, it is best to use base 10, otherwise the value obtained will be octal.
Copy code The code is as follows:

var iNum1 = parseInt("010"); // returns 8
var iNum2 = parseInt("010",8); //returns 8
var iNum3 = parseInt("010",10); //returns 10

parseFloat The () 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 a number. For this method, the first decimal point is a valid character. If two decimal points are used, the second decimal point will be considered invalid. Another difference in using this method is that the string must represent a floating point number in decimal form.
Copy code The code is as follows:

var fNum1 = parseFloat("1234blue"); //returns 1234.0
var fNum2 = parseFloat("0xA"); //returns NaN
var fNum3 = parseFloat("22.5"); //returns 22.5
var fNum4 = parseFloat("22.34.5");//returns 22.34
var fNum5 = parseFloat("0908");//returns NaN
var fNum6 = parseFloat("blue ");//returns NaN

3. Forced type conversion
The three types of forced type conversion available in ECMAScript are as follows:

(1).Boolean(value)
Convert the given value into Boolean type.
The Boolean() function will return true when the value to be converted is a string, non-zero number or object with at least one character. If the value is an empty string, the number 0, undefined or null, it will return false.
For example:

Copy code The code is as follows:

var b1 = Boolean("" ); // false;
var b2 = Boolean("hi");//true
var b3 = Boolean(100);//true
var b4 = Boolean(null);//false
var b5 = Boolean(0);//false
var b6 = Boolean(new Object());//true

(2).Number(value)
Convert the given value to a number (can be an integer or a floating point number).
Remember that 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 can be completely converted, Number() will determine whether to call the parseInt() method or the parseFloat() method.
For example:
Copy code The code is as follows:

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

(3).String(value)
Convert the given value into a string.
The only difference from calling the toString() method is that casting a null or undefined value produces a string without raising an error:
Copy code The code is as follows:

var s1 = String(null);//"null"
var oNull = null;
var s2 = oNull. toString();//causes an error

2. Reference type
Reference type is usually called a class, that is to say , when a reference value is encountered, the object is processed. ECMAScript defines "object definitions" that are logically equivalent to classes in other programming languages.

1.Object class
All classes in ECMAScript are inherited from this class, and all properties and methods in the Object class will appear in other classes (overridden).

Attributes of Object class:

(1).Constructor----Reference (pointer) to the function that creates the object. For the Object class, this pointer points to the original object() function.

(2).Prototype----A reference to the object prototype of the object. For all classes, it returns an instance of the Object object by default.

Methods of Object class:

(1).HasOwnProperty(property)----Determine whether the object has a specific property. The property must be specified as a string (for example: o.hasOwnProperty("name")).

(2).IsPrototypeOf(object)----Determine whether the object is the prototype of another object.

(3).PropertyIsEnumerable(property)----Determine whether the given property can be enumerated using the for..in statement.

(4).ToString()----Returns the original string representation of the object. Different ECMAScript implementations have different values.

(5).ValueOf()----Returns the original value that best fits the object. For many classes, the value returned by this method is the same as the return value of toString().

2. Boolean class
Boolean objects are rarely used in ECMAScript, and even if they are used, they are not easy to understand.
For example:

Copy code The code is as follows:

var oFalseObject = new Boolean(false );
var bResult = oFalseObject && true;//outputs true;

Reason: In Boolean expressions, all objects will be automatically converted to true.

3.Number class
Number.MAX_VALUE and other special values ​​are static attributes of the Number class. To get the original value of Number of a numeric object, just use the valueOf() method:
var iNumber = oNumberObject.valueOf();
In addition to the standard methods inherited from the Object class, the Number class has several other methods for processing numeric values. special method.

toFixed() method:
returns a string representation of a number with the specified number of decimal places. The method can represent numbers with 0 to 20 decimal places. Values ​​outside this range will cause an error.
For example:

Copy code The code is as follows:

var oNumberObject = new Number(99 );
aler(oNumberObject.toFixed(2));//outputs "99.00"

toExponential() method:
returns a number expressed in scientific notation String form. This method also takes a parameter that specifies the number of decimal places to output. For example:
Copy code The code is as follows:

var oNumberObj = new Number(99);
alert(oNumberObj.toExponential(1));//outputs "9.9e 1"

toPrecision() method:
Returns the predetermined form of the number according to the most meaningful form or Exponential form. It has one argument, which is the total number of digits used to represent the number (excluding the exponent).
Copy code The code is as follows:

var oNumberObj = new Number(99);
alert(oNumberObj.toPrecision(1));//outputs "1e 2" ==100

It can be seen that the toPrecision() method will round the number to get as close to the reality as possible The number of values.
For example:
Copy code The code is as follows:

var oNumberObj = new Number(99 );
alert(oNumberObj.toPrecision(2));// outputs "99"
alert(oNumberObj.toPrecision(3));// outputs "99.0"

toFixed (), toExponential(), and toPrecision() methods all perform rounding operations to correctly represent a number with the correct number of decimal places.

toLocaleString() method:
can be displayed in a format on the page, for example, 5210.50 is displayed as 5,210.50, but if its value is used, parseFloat($("N_YJJE").value.replace(//, /g, "")); replace the comma and get its value.

Note: Similar to Boolean objects, Number objects are also important, but they should be used sparingly to avoid potential problems. Whenever possible, use the raw representation of numbers.

4. String class
The valueOf() method and toString() method of String object will return the original value of String type:

Copy code The code is as follows:

alert(oStringObj.valueOf() == oStringObj.toString());//outputs "true"

String class has attribute length, which is the number of characters in the string:
Copy code The code is as follows:

var oStringObj = new String("hello world");
alert(oStringObj.length);outputs "11"

Note: Even if the string contains double Byte characters, each character is only counted as one character.

charAt() method:
returns a string containing the character at the specified position:

Copy code The code is as follows:

var oStringObj = new String("hello world");
alert(oStringObj.charAt(1));outputs "e"

charCodeAt() method:
returns a string containing the character code at the specified position:
Copy code The code is as follows :

var oStringObj = new String("hello world");
alert(oStringObj.charCodeAt(1));outputs "101"

concat() method:
is used to concatenate one or more strings to the original value of the String object. The original String object remains unchanged.
Copy code The code is as follows:

var oStringObj = new String("hello ");
var sResult = oStringObj.concat("world");//oStringObj "world"; more common
alert(sResult);//outputs "hello world"
alert(oStringObj);//outputs " hello"

The indexOf() and lastIndexOf() methods return the position of the specified substring in another string (or -1, if the substring is not found). The difference between these two methods is that indexOf() starts to search the substring from the beginning of the string (position 0), while lastIndexOf() starts to search the substring from the end of the string.

localeCompare(), compares strings (compare in alphabetical order, the later ones are larger). This method has one parameter - the string to be compared, and returns one of the following three values:
1. If the String object is arranged alphabetically before the string in the parameter, a negative number is returned (the most common is -1, but the actual return is implementation determined).
2. If the String object is equal to the string in the parameter, return 0.
3. If the String object is arranged alphabetically after the string in the parameter, return a positive number (the most common is 1, but the actual return is determined by the implementation)

slice() and substring() methods:
These two methods return substrings of the string to be processed, and both accept one or two parameters. The first parameter is the starting position of the substring to be obtained, and the second parameter is the position before the end of the substring is to be obtained (the characters at the terminal position are not included in the returned value). If the second argument is omitted, the termination bit defaults to the length of the string. Neither of these methods changes the value of the String object itself.

Copy code The code is as follows:

var oStringObj = new String("hello world");
alert(oStringObj.slice(3));//outputs "lo world"
alert(oStringObj.slice(3,7));//outputs "lo w"

Note: For negative parameters, the slice() method will add the length of the string to the parameter, and the substring() method will treat it as 0 (that is, it will be ignored).
Copy code The code is as follows:

var oStringObj = new String("hello world");
alert(oStringObj.slice(-3));//outputs "rld" is equivalent to taking the reverse
alert(oStringObj.substring(-3));//outputs "hello world"
alert (oStringObj.slice(3,-4));//outputs "lo w"
alert(oStringObj.substring(3,-4));//outputs "hel" substring() always replaces the smaller The number serves as the starting bit, and the larger number serves as the ending bit.

toLowerCase(), toLocalLowerCase(), toUpperCase() and toLocaleUpperCase():
The first two methods convert the string into all lowercase, and the latter two methods are used to convert the string Complete in capital letters. The toLocalLowerCase() and toLocaleUpperCase() methods are implemented based on specific regions.

Remember: All properties and methods of the String class can be applied to String primitive values ​​because they are pseudo-objects.

5. instanceof operator
There is a problem when using the typeof operator to store values ​​in reference types. No matter what type of object is referenced, it returns "object". The instanceof method requires developers to explicitly confirm that the object is of a specific type. For example:

Copy code The code is as follows:

var oStrObj = new String("hello world" );
alert(oStrObj instanceof String);//outputs "true"
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)
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
1 months ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
1 months 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)

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

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

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

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

How to create a stock candlestick chart using PHP and JS How to create a stock candlestick chart using PHP and JS Dec 17, 2023 am 08:08 AM

How to use PHP and JS to create a stock candle chart. A stock candle chart is a common technical analysis graphic in the stock market. It helps investors understand stocks more intuitively by drawing data such as the opening price, closing price, highest price and lowest price of the stock. price fluctuations. This article will teach you how to create stock candle charts using PHP and JS, with specific code examples. 1. Preparation Before starting, we need to prepare the following environment: 1. A server running PHP 2. A browser that supports HTML5 and Canvas 3

How do generic functions handle pointers and reference types in Golang? How do generic functions handle pointers and reference types in Golang? Apr 16, 2024 pm 04:06 PM

When a generic function handles pointer types in Go, it will receive a reference to the original variable, allowing the variable value to be modified. Reference types are copied when passed, making the function unable to modify the original variable value. Practical examples include using generic functions to compare strings or slices of numbers.

Type conversion of golang function Type conversion of golang function Apr 19, 2024 pm 05:33 PM

In-function type conversion allows data of one type to be converted to another type, thereby extending the functionality of the function. Use syntax: type_name:=variable.(type). For example, you can use the strconv.Atoi function to convert a string to a number and handle errors if the conversion fails.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

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

Implicit type conversion: An exploration of different variations of types and their applications in programming Implicit type conversion: An exploration of different variations of types and their applications in programming Jan 13, 2024 pm 02:54 PM

Explore the different types of implicit type conversions and their role in programming Introduction: In programming, we often need to deal with different types of data. Sometimes, we need to convert one data type to another type in order to perform a specific operation or meet specific requirements. In this process, implicit type conversion is a very important concept. Implicit type conversion refers to the process in which the programming language automatically performs data type conversion without explicitly specifying the conversion type. This article will explore the different types of implicit type conversions and their role in programming,

The relationship between js and vue The relationship between js and vue Mar 11, 2024 pm 05:21 PM

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

See all articles