1. Type conversion
1.Convert to string
The interesting thing about ECMAScript's Boolean values, numbers, and string primitives is that they are pseudo-objects, which means they actually have properties and methods.
like:
Copy the code code as follows:
var sColor = "blue";
alert(sColor.length);//outputs "4"
In summary, the three main primitive values, Boolean values, numbers, and strings, all 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 the 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, namely the default mode and the base mode. Using the default mode, the toString() method only uses the corresponding string to output the numerical value (whether it is an integer, floating point number or scientific notation). number method).
Copy the 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's toString() method, numbers can be output in different bases (bases).
Copy the 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 numbers
ECMAScript provides two methods for converting 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. All other types will return NaN.
For example:
Copy the 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 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 the code code 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 you will get an octal value.
Copy the code code as follows:
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. 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 the 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. Forced type conversion
The 3 types of casts available in ECMAScript are as follows:
(1).Boolean(value)
Convert the given value to Boolean type.
The Boolean() function returns 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.
like:
Copy the code code 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)
Converts the given value to a number (can be an integer or a floating point number).
Also 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.
like:
Copy the 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)
Convert the given value to 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 the code code as follows:
var s1 = String(null);//"null"
var oNull = null;
var s2 = oNull.toString();//causes an error
2. Reference type
Reference types are usually called classes, which means that 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).
Properties 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 attribute. 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 suits 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, they are not easy to understand.
For example:
Copy the code code as follows:
var oFalseObject = new Boolean(false);
var bResult = oFalseObject && true;//outputs true;
Reason: In Boolean expressions, all objects are automatically converted to true.
3.Number class
Special values such as Number.MAX_VALUE are static properties 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 specialized methods for handling numerical values.
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.
like:
Copy the code code as follows:
var oNumberObject = new Number(99);
aler(oNumberObject.toFixed(2));//outputs "99.00"
toExponential() method:
Returns the string representation of the number in scientific notation. This method also takes a parameter that specifies the number of decimal places to output. For example:
Copy the code code as follows:
var oNumberObj = new Number(99);
alert(oNumberObj.toExponential(1));//outputs "9.9e+1"
toPrecision() method:
Returns a predetermined or exponential form of a number, depending on which form makes the most sense. It has one argument, which is the total number of digits used to represent the number (excluding the exponent).
Copy the code code as follows:
var oNumberObj = new Number(99);
alert(oNumberObj.toPrecision(1));//outputs "1e+2" ==100
As can be seen, the toPrecision() method rounds the number to get a number as close to the true value as possible.
like:
Copy the 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 all perform rounding operations to correctly represent a number with the correct number of decimal places.
toLocaleString() method:
It can be displayed in the format on the page, for example, 5210.50 is displayed as 5,210.50, but if its value is used, it should be replaced in the form of parseFloat($("N_YJJE").value.replace(//,/g, "")); Remove 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 the String object both return the original value of the String type:
Copy the code code as follows:
alert(oStringObj.valueOf() == oStringObj.toString());//outputs "true"
The String class has the attribute length, which is the number of characters in the string:
Copy the 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 counts as only one character.
charAt() method:
Returns a string containing the character at the specified position:
Copy the 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 position:
Copy the code code as follows:
var oStringObj = new String("hello world");
alert(oStringObj.charCodeAt(1));outputs "101"
concat() method:
Used to concatenate one or more strings to the original value of a String object. The original String object remains unchanged.
Copy the 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 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 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 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:
Both 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 the code code as follows:
var oStringObj = new String("hello world");
alert(oStringObj.slice(3));//outputs "lo world"
alert(oStringObj.slice(3,7));//outputs "low"
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 the code code as follows:
var oStringObj = new String("hello world");
alert(oStringObj.slice(-3));//outputs "rld" is equivalent to reverse fetching
alert(oStringObj.substring(-3));//outputs "hello world"
alert(oStringObj.slice(3,-4));//outputs "lo w"
alert(oStringObj.substring(3,-4));//outputs "hel" substring() always uses the smaller number as the starting bit and the larger number 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 into all uppercase. 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 reference type to store values when using the typeof operator. 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. like:
Copy the code code as follows:
var oStrObj = new String("hello world");
alert(oStrObj instanceof String);//outputs "true"