Js type conversion and reference types (Boolean/Number/String)

Source: Internet
Author: User

I. type conversion

1. Convert to string

ECMAScript's Boolean values, numbers, and string values are interesting because they are pseudo objects, which means they actually have attributes and methods.
For example:
Js Code
Var sColor = "blue ";
Alert (sColor. length); // outputs "4"
[Js] view plaincopy
Var sColor = "blue ";
Alert (sColor. length); // outputs "4"


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

The toString () method of the Boolean type only outputs "true" or "false", and the result is determined by the value of the variable:
Js Code
Var bFound = false;
Alert (bFound. toString (); // outputs "false"
[Js] view plaincopy
Var bFound = false;
Alert (bFound. toString (); // outputs "false"


The toString () method of the Number type is special. It has two modes: default mode and base mode. The default mode and toString () mode are used () the method outputs the numeric value (whether it is an integer, floating point number, or scientific Notation) with the corresponding string ).
Js Code
Var iNum1 = 10;
Var fNum2 = 10.0;
Alert (iNum1.toString (); // outputs "10"
Alert (fNum2.toString (); // outputs "10"
[Js] view plaincopy
Var iNum1 = 10;
Var fNum2 = 10.0;
Alert (iNum1.toString (); // outputs "10"
Alert (fNum2.toString (); // outputs "10"


The base mode of the toString () method of the Number type can be used to output numbers with different base (base) numbers.
Js Code
Var iNum = 10;
Alert (iNum. toString (2); /// outputs "1010"
Alert (iNum. toString (8); // outputs "12"
Alert (iNum. toString (16); // outputs ""
[Js] view plaincopy
Var iNum = 10;
Alert (iNum. toString (2); /// outputs "1010"
Alert (iNum. toString (8); // outputs "12"
Alert (iNum. toString (16); // outputs ""


2. convert to a number

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

For example:
Js Code
Var iNum1 = parseInt ("1234 blue"); // returns 1234
Var iNum2 = parseInt ("oxA"); // returns 10
Var iNum3 = parseInt ("22.5"); // returns 22
Var iNum4 = parseInt ("blue"); // returns NaN
[Js] view plaincopy
Var iNum1 = parseInt ("1234 blue"); // 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 the base mode, which can convert binary, octal, hexadecimal, or any other hexadecimal string to a decimal integer. The second parameter specifies which method to parse.
Js Code
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
[Js] view plaincopy
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 0, it is best to use base 10; otherwise, the octal value is obtained.
Js Code
Var iNum1 = parseInt ("010"); // returns 8
Var iNum2 = parseInt ("010", 8); // returns 8
Var iNum3 = parseInt ("010", 10); // returns 10
[Js] view plaincopy
Var iNum1 = parseInt ("010"); // returns 8
Var iNum2 = parseInt ("010", 8); // returns 8
Var iNum3 = parseInt ("010", 10); // returns 10


The parseFloat () method is similar to the parseInt () method. Each character is viewed from position 0 until the first invalid character is found, then, convert the string before the character to a number. For this method, the first decimal point is a valid character. If two decimal points are used, the second decimal point is considered invalid. Another difference with this method is that the string must represent a floating point number in decimal format.

Js Code
Var fNum1 = parseFloat ("1234 blue"); // 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
[Js] view plaincopy
Var fNum1 = parseFloat ("1234 blue"); // 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 mandatory conversions available in ECMAScript are as follows:
(1). Boolean (value)
Converts a given value to a Boolean value.
If the value to be converted is a string of at least one character, a non-zero number, or an object, the Boolean () function returns true. If the value is a null String, number 0, undefined, or null, it returns false.
For example:
Js Code
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
[Js] view plaincopy
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)
Converts a given value to a number (which can be an integer or a floating point number ).
Remember that the parseInt () and parseFloat () methods only convert strings before the first invalid character, so "4.5.6" will be converted to "4.5 ". Use Number () for forced type conversion. "4.5.6" will return NaN because the entire string value cannot be converted to a Number. If the string can be fully converted, Number () determines whether to call the parseInt () method or the parseFloat () method.
For example:
Js Code
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
[Js] view plaincopy
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)
Converts a given value to a string.
The only difference from calling the toString () method is that forced type conversion of null or undefined values can generate a string without causing an error:
Js Code
Var s1 = String (null); // "null"
Var oNull = null;
Var s2 = oNull. toString (); // causes an error
[Js] view plaincopy
Var s1 = String (null); // "null"
Var oNull = null;
Var s2 = oNull. toString (); // causes an error


Ii. Reference Type
A 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", which are logically equivalent to classes in other programming languages.

1. Object Class
All classes in ECMAScript are inherited from this class, And all attributes and methods in the Object class will appear in other classes (overwritten ).

Attributes of the Object class:

(1). Constructor ---- reference (pointer) to the function of the created object ). For Object classes, this pointer points to the original object () function.

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

Object Class method:

(1). HasOwnProperty (property) ---- determines whether an object has a specific property. This attribute must be specified with a string (for example, o. hasOwnProperty ("name ")).

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

(3). PropertyIsEnumerable (property) ---- determines 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 () ---- return the original value most suitable for this 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, which is hard to understand even when used.
For example:
Js Code
Var oFalseObject = new Boolean (false );
Var bResult = oFalseObject & true; // outputs true;
[Js] view plaincopy
Var oFalseObject = new Boolean (false );
Var bResult = oFalseObject & true; // outputs true;


Cause: In a Boolean expression, all objects are automatically converted to true.

3. Number class

Special values such as Number. MAX_VALUE are static attributes of the Number class. To obtain the original Number value of a numeric object, you only need to use the valueOf () method:
Var iNumber = oNumberObject. valueOf ();
In addition to the standard methods inherited from the Object class, the Number class also has several special methods for processing numerical values.

ToFixed () method:
Returns a string representation of digits with the specified decimal digits. It indicates a number with 0 to 20 decimal places. If the value exceeds this range, an error is thrown.
For example:
Js Code
Var oNumberObject = new Number (99 );
Aler (oNumberObject. toFixed (2); // outputs "99.00"
[Js] view plaincopy
Var oNumberObject = new Number (99 );
Aler (oNumberObject. toFixed (2); // outputs "99.00"


ToExponential () method:
The return value is a string of numbers expressed in scientific notation. This method also has a parameter that specifies the number of decimal places to be output. For example:
Js Code
Var oNumberObj = new Number (99 );
Alert (oNumberObj. toExponential (1); // outputs "9.9e + 1"
[Js] view plaincopy
Var oNumberObj = new Number (99 );
Alert (oNumberObj. toExponential (1); // outputs "9.9e + 1"


ToPrecision () method:
Returns the predefined or exponential form of A number based on the most meaningful form. It has a parameter that represents the total number (excluding the exponent) of a number ).
Js Code
Var oNumberObj = new Number (99 );
Alert (oNumberObj. toPrecision (1); // outputs "1e + 2" = 100
[Js] view plaincopy
Var oNumberObj = new Number (99 );
Alert (oNumberObj. toPrecision (1); // outputs "1e + 2" = 100
As you can see, the toPrecision () method rounds the logarithm to get the number as close as possible to the actual value.
For example:
Js Code
Var oNumberObj = new Number (99 );
Alert (oNumberObj. toPrecision (2); // outputs "99"
Alert (oNumberObj. toPrecision (3); // outputs "99.0"
[Js] view plaincopy
Var oNumberObj = new Number (99 );
Alert (oNumberObj. toPrecision (2); // outputs "99"
Alert (oNumberObj. toPrecision (3); // outputs "99.0"


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

ToLocaleString () method:
The format can be displayed on the page. For example, if 5210.50 is displayed as 5,210.50, parseFloat ($ ("N_YJJE") should be used when its value is used "). value. replace (/\,/g.

Note: similar to a Boolean object, a Number object is also important, but this object should be used less to avoid potential problems. The original numeric notation is used whenever possible.

4. String class

Both the valueOf () method and toString () method of the String object return the original value of the String type:
Js Code
Alert (oStringObj. valueOf () = oStringObj. toString (); // outputs "true"
[Js] view plaincopy
Alert (oStringObj. valueOf () = oStringObj. toString (); // outputs "true"


The String class has the attribute length, which is the number of characters of the String:
Js Code
Var oStringObj = new String ("hello world ");
Alert (oStringObj. length); outputs "11"
[Js] view plaincopy
Var oStringObj = new String ("hello world ");
Alert (oStringObj. length); outputs "11"


Note: even if the string contains double-byte characters, each character is only one character.

CharAt () method:
The returned string contains the characters at the specified position:
Js Code
Var oStringObj = new String ("hello world ");
Alert (oStringObj. charAt (1); outputs "e"
[Js] view plaincopy
Var oStringObj = new String ("hello world ");
Alert (oStringObj. charAt (1); outputs "e"


CharCodeAt () method:
The returned string contains the character code at the specified position:
Js Code
Var oStringObj = new String ("hello world ");
Alert (oStringObj. charCodeAt (1); outputs "101"
[Js] view plaincopy
Var oStringObj = new String ("hello world ");
Alert (oStringObj. charCodeAt (1); outputs "101"


Concat () method:
Connects one or more strings to the original value of the String object. The original String object remains unchanged.
Js Code
Var oStringObj = new String ("hello ");
Var sResult = oStringObj. concat ("world"); // oStringObj + "world"; more common
Alert (sResult); // outputs "hello world"
Alert (oStringObj); // outputs "hello"
[Js] view plaincopy
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 this substring is not found ). The difference between the two methods is greater than that, indexOf () is to retrieve the substring from the beginning of the string (position 0), and lastIndexOf () the substring is retrieved from the end of the string.

LocaleCompare () to compare strings (in alphabetical order, the greater the value after the comparison ). This method has a parameter -- the string to be compared, and returns one of the following three values:
1. If the String object is placed before the String in the parameter in alphabetical order, a negative number is returned (-1 is the most common, but the actual return is determined by the implementation ).
2. If the String object is equal to the String in the parameter, 0 is returned.
3. If the String object is placed after the String in the parameter in alphabetical order, return a positive number (the most common is 1, but the actual return is determined by the implementation)

Slice () and substring () methods:
The two methods return the substrings of the strings to be processed and both of them 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 substring is terminated (the character at the ending position does not include the value returned by the large value ). If the second parameter is omitted, the end bit is the string length by default. Both methods do not change the value of the String object.
Js Code
Var oStringObj = new String ("hello world ");
Alert (oStringObj. slice (3); // outputs "lo world"
Alert (oStringObj. slice (3, 7); // outputs "lo w"
[Js] view plaincopy
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 adds a parameter to the length of the string, and the substring () method treats it as 0 (that is, it will be ignored ).
Js Code
Var oStringObj = new String ("hello world ");
Alert (oStringObj. slice (-3); // outputs "rld" is equivalent to reverse fetch
Alert (oStringObj. substring (-3); // outputs "hello world"
Alert (oStringObj. slice (3,-4); // outputs "lo w"
Alert (oStringObj. substring (3,-4); // outputs "El" substring () always uses a smaller number as the start position, and a larger number as the end position.
[Js] view plaincopy
Var oStringObj = new String ("hello world ");
Alert (oStringObj. slice (-3); // outputs "rld" is equivalent to reverse fetch
Alert (oStringObj. substring (-3); // outputs "hello world"
Alert (oStringObj. slice (3,-4); // outputs "lo w"
Alert (oStringObj. substring (3,-4); // outputs "El" substring () always uses a smaller number as the start position, and a larger number as the end position.

 

ToLowerCase (), toLocalLowerCase (), toUpperCase (), and toLocaleUpperCase ():
The first two methods are used to convert the string to lowercase, and the last two methods are used to convert the string to uppercase. The toLocalLowerCase () and toLocaleUpperCase () methods are implemented based on specific regions.

Remember: All attributes and methods of the String class can be applied to the original values of the String because they are pseudo objects.

Match (): finds matching of one or more regular expressions.
Javascript code
'My name is CJ. Hello everyone! '. Match (/[A-Z]/g); // M, C, J, H
[Javascript] view plaincopy
'My name is CJ. Hello everyone! '. Match (/[A-Z]/g); // M, C, J, H

Replace (): replace the substring that matches the regular expression.
Search (): searches for values that match the regular expression.
Javascript code
'Age is 18. Golden '. search (/\ d +/); // 7
[Javascript] view plaincopy
'Age is 18. Golden '. search (/\ d +/); // 7

Split (): Splits a string into a string array.

5. instanceof operator www.2cto.com

When using the typeof operator to store values of the reference type, a problem occurs. No matter what type of object is referenced, it returns "object ". The instanceof method requires the developer to explicitly confirm that the object is of a specific type. For example:
Js Code
Var oStrObj = new String ("hello world ");
Alert (oStrObj instanceof String); // outputs "true"

Author: clever027

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.