Home  >  Article  >  Web Front-end  >  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

WBOY
WBOYOriginal
2016-05-16 16:56:321104browse

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:
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