JS type conversion and reference type explanation (boolean_number_string) _javascript tips

Source: Internet
Author: User
Tags hasownproperty

One, type conversion

1. Convert to String
The interesting thing about ECMAScript's Boolean values, numbers, and the original values of strings is that they are pseudo objects, which means they actually have properties and methods.
Such as:

Copy Code code as follows:

var scolor = "Blue";
alert (scolor.length);//outputs "4"

All in all, 3 of the primary values Boolean values, numbers, and strings have the ToString () method. All objects defined by ECMAScript have the ToString () method, whether it is a pseudo object or a true object.

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

Copy Code code as follows:

var bfound = false;
Alert (bfound.tostring ());//outputs "false"

The ToString () method of the number type is special, it has two modes, the default mode and the base mode, the default mode, and the ToString () method simply outputs numeric values (whether integers, floating-point numbers, or scientific notation) with the corresponding string.
Copy Code code as follows:

var iNum1 = 10;
var fNum2 = 10.0;
Alert (inum1.tostring ()); Outputs "10"
Alert (fnum2.tostring ()); Outputs "10"

Using the base mode of the number type ToString () method, you can output numbers in different bases (in radix).
Copy Code code 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 Digital
ECMAScript provides two methods for converting a non-numeric original value into a number, namely parseint () and parsefloat ().
Note: These methods are called only for string type (except number) to correctly run Nan for other types.

For example:

Copy Code code 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 pattern that converts binary, octal, hexadecimal, or any other string of strings into decimal integers. The second parameter specifies which system to parse.
Copy Code code as follows:

var iNum1 = parseint ("AF";)//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 a leading 0, it is best to use cardinality 10, otherwise the octal value is obtained.
Copy Code code as follows:

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

The Parsefloat () method works like the parseint () method, viewing each character starting at position 0 until the first inactive character is found, and then converting the string before the character to a number. For this method, the first decimal point that appears is a valid character. If you use two decimal points, the second decimal point is considered invalid. Another difference in using this method is that the string must represent a floating-point number in decimal form.
Copy Code code 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. Force type Conversions
The 3 mandatory type conversions available in ECMAScript are as follows:

(1). Boolean (value)
Converts a given value to a Boolean.
The Boolean () function returns True when the value to be converted is a string of at least one character, a number other than 0 digits, or an object. If the value is an empty string, number 0, undefined, or null, it returns FALSE.
Such as:

Copy Code code as follows:

var B1 = Boolean (""); False
var b2 = Boolean ("Hi");//true
var B3 = Boolean (m);//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 (can be an integer or floating point count).
Remember that the parseint () and parsefloat () methods only convert the string before the first invalid character, so "4.5.6" is converted to "4.5". Force type conversion with number (), and "4.5.6" returns Nan, because the entire string value cannot be converted to numbers. If the string can be completely converted, number () will determine whether to call the parseint () method or call the Parsefloat () method.
Such as:
Copy Code code 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)
Converts a given value to a string.
The only difference from invoking the ToString () method is that coercion of a type cast on a null or undefined value can generate a string without raising an error:
Copy Code code as follows:

var S1 = String (null);//"NULL"
var onull = null;
var s2 = onull.tostring ();//causes an error

ii. type of reference
Reference types are usually called classes (class), which means that when you encounter a reference value, you are dealing with an object. ECMAScript defines an "object definition" that is logically equivalent to a class in another programming language.

1.Object class
All classes in ECMAScript are inherited by this class, and all the properties and methods in the object class appear in other classes (overwritten).

Properties of the object class:

(1). constructor----A reference (pointer) to the function that created the object. For the object class, the pointer points to the original object () function.

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

method of object class:

(1). The hasOwnProperty (property)----Determine whether an object has a specific attribute. This property 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----Determine whether a given property can be used for ... In statement to enumerate.

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

(5). valueof ()----Returns the original value that best fits the object. For many classes, the method returns the same value as the return value of ToString ().

2.Boolean class
A Boolean object is rarely used in ECMAScript, and is not easily understood even when used.
For example:

Copy Code code as follows:

var ofalseobject = new Boolean (false);
var bresult = Ofalseobject && true;//outputs true;

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

3.Number class
Number.MAX_VALUE and so on special values are the static properties of the number class. To get number raw values for 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 has several specialized methods for handling numeric values.

ToFixed () Method:
Returns a string representation of a number with a specified number of decimal digits. Method can represent a number with 0 to 20 decimal digits, and a value that is outside this range throws an error.
Such as:

Copy Code code as follows:

var onumberobject = new number (99);
Aler (onumberobject.tofixed (2));//outputs "99.00"

Toexponential () Method:
Returns the string form of a number represented by scientific notation. The method also has a parameter that specifies the number of decimal places to output. For example:
Copy Code code as follows:

var onumberobj = new number (99);
Alert (onumberobj.toexponential (1));//outputs "9.9e+1"

Toprecision () Method:
Returns the predetermined form or exponential form of a number according to the most meaningful form. It has a parameter, which is the total number of digits (excluding exponents) that are used to represent the number.
Copy Code code as follows:

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 as close to the actual value as possible.
Such as:
Copy Code code as follows:

var onumberobj = new number (99);
Alert (Onumberobj.toprecision (2));//outputs "99"
Alert (Onumberobj.toprecision (3));//outputs "99.0"

The toFixed (), toexponential (), and Toprecision () methods perform rounding to correctly represent a number with the correct number of decimal digits.

toLocaleString () Method:
Can be formatted on the page, such as 5210.50 displayed as 5,210.50, but if you use its value, you should replace the comma with parsefloat ($ ("N_yjje"). Value.replace (//,/g, ""));

Note: A number object is also important, similar to a Boolean object, but you should use this object sparingly to avoid potential problems. Use the original notation of numbers whenever possible.

4.String class
Both the valueof () method and the ToString () method of a String object return the original value of the string type:

Copy Code code as follows:

Alert (ostringobj.valueof () = = Ostringobj.tostring ());//outputs "true"

The string class has the attribute length, which is the number of characters for the string:
Copy Code code 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 counted as a single character.

CharAt () Method:
Returns a string containing the character at the specified position:

Copy Code code 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 location:
Copy Code code as follows:

var ostringobj = new String ("Hello World");
Alert (Ostringobj.charcodeat (1)); outputs "101"

Concat () Method:
Used to connect one or more strings to the original values of a string object. The original string object does not change.
Copy Code code 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 differences between the two methods are greater than the indexOf (), which retrieves the substring starting at the beginning of the string (position 0), while LastIndexOf () retrieves the substring from the end of the string.

Localecompare (), the string is compared (in alphabetical order, the later the larger). The method has one argument-the string to compare, and returns one of the following 3 values:
1. Returns a negative number (most commonly-1, although the true return is determined by the implementation) if the string object is in alphabetical order before the strings in the argument.
2. If the string object is equal to the strings in the argument, returns 0.
3. Returns a positive number (most commonly 1, although the true return is determined by the implementation) if the string object is in alphabetical order after the strings in the argument.

Slice () and substring () methods:
Both methods return a substring of the string to be processed, accepting one or two arguments. The first argument is the starting position of the substring to get, and the second parameter is the position before the substring terminates (the character at the end position does not include the value that is returned in the large return). 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 code 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 arguments, the slice () method uses the length of the string plus the arguments, and the substring () method handles it as 0 (that is, it is ignored).
Copy Code code as follows:

var ostringobj = new String ("Hello World");
Alert (Ostringobj.slice ( -3));//outputs "Rld" is equivalent to 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 takes the smaller number as the starting bit and the larger number as the terminating bit.

toLowerCase (), Tolocallowercase (), toUpperCase () and toLocaleUpperCase ():
The first two methods 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 a specific region.

Remember that all properties and methods of the string class can be applied to string raw values because they are pseudo objects.

5.instanceof operator
Storing a value using a reference type when using the TypeOf operator can cause an issue that returns "Object" regardless of what type of object is referenced. The Instanceof method shows that the developer explicitly confirms that the object is a specific type. Such as:

Copy Code code as follows:

var ostrobj = new String ("Hello World");
Alert (ostrobj instanceof String);//outputs "true"

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.