Js type conversion and reference type specification of Boolean_Number_String

  • 2020-03-30 02:19:21
  • OfStack

I. type conversion

1. Convert to a string
What's interesting about the original values of Boolean values, Numbers, and strings in ECMAScript is that they are pseudo-objects, which means they actually have properties and methods.
Such as:

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

All in all, the three main primitive 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 simply outputs "true" or "false", and the result is determined by the value of the variable:

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. In the default mode, the toString() method simply outputs numeric values (whether integer, floating point, or scientific notation) with the corresponding string.

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

The base pattern of the toString() method of type Number can output Numbers with different bases (base cardinality).

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 ways to convert non-numeric primitive values into Numbers: parseInt () and parseFloat ().
Note: only if these methods are called for String types (except Number) can they be run correctly and return NaN for all other types.

Such as:

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 that converts binary, octal, hexadecimal, or any other decimal string to a decimal integer. The second parameter specifies which base to parse in.

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 a leading 0, it is best to use base 10, otherwise you get an octal value.

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 in that it looks at each character from position 0 until it finds the first non-valid character, and then converts the string before that character into a number. For this method, the first decimal point to appear is a valid character. If you use two decimal points, the second decimal point will be considered invalid. Another difference with this method is that the strings must represent floating point Numbers in decimal form.

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. Cast
The three casts available in ECMAScript are as follows:

(1). A Boolean (value)
Converts the given value to a Boolean type.
The Boolean() function returns true when the value to be converted is a string with at least one character, a non-zero digit, or an object. If the value is an empty string, the number 0, undefined, or null, it returns false.
Such as:

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 (either 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". Cast with Number(), "4.5.6" returns 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.
Such as:

Number(new Object());//NaN

(3). The String (value)
Converts a given value to a string.
The only difference from calling the toString() method is that casting a null or undefined value generates a string without causing an error:

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

2. Reference type
A reference type is usually called a class, which means that when you encounter a reference value, you are dealing with an object. ECMAScript defines "object definitions," which are logically equivalent to classes in other programming languages.

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

Properties of the Object class:

Constructor-- a reference (pointer) to a function that creates an object. For the Object class, this pointer points to the original Object () function.

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

Method of the Object class:

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

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

(3).PropertyIsEnumerable(property)-- determines whether a given property can be used for.. The in statement enumerates.

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

(5).ValueOf()-- returns the original value that is most appropriate for the object. For many classes, this method returns the same value as toString().

2. The Boolean type
Boolean objects are rarely used in ECMAScript and are difficult to understand if used.
Such as:

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

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

3. The Number class
Special values such as number.max_value are static properties of the Number class. To get the original Number valueOf the Number object, just use the valueOf() method:
Var iNumber = oNumberObject. The 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 the specified number of decimal places. Method can represent Numbers with 0 to 20 decimal places, and values outside this range will cause an error.
Such as:

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

ToExponential () method:
Returns a string representation of a number in scientific notation. The method also takes an argument specifying the number of decimal places to output. Such as:

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

ToPrecision () method:
Returns the predetermined or exponential form of a number in terms of the most meaningful form. It takes a parameter, the total number of Numbers used to represent the number (not including the exponent).

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

As you can see, the toPrecision() method rounds logarithmically to get as close to the true value as possible.
Such as:

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

ToFixed (), toExponential () and the toPrecision () method for rounding operation, in order to correctly said a number of decimal digits with correct.

ToLocaleString () method:
It can be formatted on the page, such as 5210.50 as 5,210.50, but if you use its value, you should use parseFloat($("N_YJJE").value.replace(//,/g, ""); Replace the comma with the form of.

Note: like a Boolean object, the Number object is also important, but should be used sparingly to avoid potential problems. Whenever possible, use the original representation of Numbers.

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

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

The String class has the property length, which is the number of characters in the String:

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

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

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

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:

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 stays the same.

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

The indexOf() and lastIndexOf() methods both return the location of the specified substring in another string (or -1, if the substring was not found). The difference between the two methods is greater than that indexOf() retrieves the substring from the beginning of the string (position 0), while lastIndexOf() retrieves the substring from the end of the string.

LocaleCompare (), which compares strings (in alphabetical order, larger). This method takes one argument -- the string to be compared returns one of the following three values:
1. If the String object is placed alphabetically before the String in the argument, it returns a negative number (the most common is -1, but the actual return is up to the implementation).
Returns 0 if the String object is equal to the String in the argument.
3. If the String object is placed alphabetically after the String in the argument, it returns a positive number (most commonly 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 each takes one or two arguments. The first parameter is the starting position of the substring to get, and the second parameter is the position to get before the substring terminates (the character at the termination position does not include the value returned by the large). If the second parameter is omitted, the termination bit defaults to the length of the string. Neither method changes the value of the String object itself.

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 the length of the string to the argument, and the substring() method treats it as a 0 (that is, it ignores it).

var oStringObj = new String("hello world");
alert(oStringObj.slice(-3));//Outputs "RLD" are equivalent to 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 have 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 strings to all lowercase, and the last two are used to convert strings to all uppercase. The toLocalLowerCase() and toLocaleUpperCase() methods are implemented on a locale-based basis.

Remember: all the properties and methods of the String class apply to the original String values because they are pseudo-objects.

5. The instanceof operator
There is a problem with using the typeof operator to store values in reference types, which return "object" regardless of the typeof object being referenced. The instanceof method shows the developer that the object is explicitly of a particular type. Such as:

var oStrObj = new String("hello world");   
alert(oStrObj instanceof String);//outputs "true" 

Related articles: