Reference Type in Javascript [w3school]

Source: Internet
Author: User
Document directory
  • An object has the following attributes:
  • The object also has several methods:
  • See
  • Tofixed () method
  • Toexponential () method
  • Toprecision () method
  • See
  • Length attribute
  • Charat () and charcodeat () Methods
  • Concat () method
  • Indexof () and lastindexof () Methods
  • Localecompare () method
  • Slice () and substring ()
  • Tolowercase (), tolocalelowercase (), touppercase (), and tolocaleuppercase ()

A reference type is usually called a class ).

This tutorial will discuss a large number of pre-defined reference types for ecmascript.

Reference Type

A reference type is usually called a class. That is to say, when a reference value is encountered, the object is processed.

This tutorial will discuss a large number of pre-defined reference types for ecmascript.

From now on, we will focus on the reference types closely related to the discussed primitive types.

Note: in the traditional sense, ecmascript does not really have classes. In fact, except that there is no class, there is no "class" in the ECMA-262. Ecmascript defines "object definitions", which are logically equivalent to classes in other programming languages.

Tip: This tutorial uses the term "object ".

An object is created by adding the name of the object to be instantiated to the new operator. For example, the following code creates an object instance:

var o = new Object();

This syntax is similar to the Java language, but when there are more than one parameter, ecmascript requires brackets. If there is no parameter, as shown in the following code, parentheses can be omitted:

var o = new Object;

Note: Although parentheses are not required, brackets are recommended to avoid confusion.

Tip: We will further explore objects and their behaviors in the object basics chapter.

This section focuses on reference types with equivalent primitive types.

Object

Object itself is not very useful, but you should understand it before learning about other classes. Because the object in ecmascript and Java
Similar to Java. Lang. Object, all objects in ecmascript are inherited from this object.
All the attributes and methods in the object will appear in other objects. Therefore, if you understand the object, you can better understand other objects.

An object has the following attributes:
Constructor
Reference (pointer) of the function used to create an object ). For an object, this pointer points to the original object () function.
Prototype
References the object prototype of the object. For all objects, it returns an instance of the object by default.
The object also has several methods:
Hasownproperty (property)
Determines whether an object has a specific attribute. This attribute must be specified with a string. (For example, O. hasownproperty ("name "))
Isprototypeof (object)
Determine whether the object is a prototype of another object.
Propertyisenumerable
Determines whether a given attribute can be enumerated using the for... in statement.
Tostring ()
Returns the original string representation of the object. For object objects, the ECMA-262 does not define this value, so different ecmascript implementations have different values.
Valueof ()
Returns the original value that best fits the object. For many objects, the value returned by this method is the same as the return value of tostring.

Note: The attributes and methods listed above are overwritten by other objects.

Boolean object

A boolean object is a reference type of the Boolean primitive type.

To create a Boolean object, you only need to pass the Boolean value as the parameter:

var oBooleanObject = new Boolean(true);

The Boolean object overwrites the valueof () method of the object, and returns the original values, that is, true and false. The tostring () method is overwritten, And the return value is "true" or "false ".

Unfortunately, Boolean objects are rarely used in ecmascript, which is hard to understand even if used.

This problem usually occurs when a Boolean object is used in a Boolean expression. For example:

VaR ofalseobject = new Boolean (false );
VaR bresult = ofalseobject & True; // Output True

In this Code, create a Boolean object with the value of false. Then, use this value and the original value true to perform the and operation. In Boolean
In the operation, the result of the "and" operation is "false" and "true. However, in this line of code, ofalseobject is calculated, not its value.
False.

As discussed earlier, in a Boolean expression, all objects are automatically converted to true, so the value of ofalseobject is true. Then, true and true are used to perform the and operation. The result is true.

Note: although you should understand the availability of Boolean objects, it is best to use the original Boolean value to avoid the problems mentioned in this section.

See

For more information about Boolean objects, see the reference manual for JavaScript Boolean objects.

Number object

As you may think, a number object is a reference type of the original number type. To create a number object, use the following code:

var oNumberObject = new Number(68);

You should have recognized the number object mentioned in the special values (such as number. max_value) mentioned in the previous section of this chapter. All special values are static attributes of the number object.

To obtain the original number value of a numeric object, you only need to use the valueof () method:

var iNumber = oNumberObject.valueOf();

Of course, the number class also has the tostring () method, which has been discussed in detail in the section about type conversion.

In addition to the standard method inherited from the object, the number object also has several special methods to process the value.

Tofixed () method

The tofixed () method returns a string representation of digits with the specified decimal digits. For example:

VaR onumberobject = new number (68 );
Alert (onumberobject. tofixed (2); // The output "68.00"

Here, the tofixed () method parameter is 2, indicating that two decimal places should be displayed. This method returns "68.00", and the Null String bit is supplemented by 0. This method is very useful for currency processing applications. The tofixed () method can represent numbers with 0 to 20 decimal places. An error occurs if the value exceeds this range.

Toexponential () method

Another method related to formatting a number is toexponential (), which returns a string of numbers represented by scientific notation.

Similar to the tofixed () method, the toexponential () method also has a parameter that specifies the number of decimal places to be output. For example:

VaR onumberobject = new number (68 );
Alert (onumberobject. toexponential (1); // output "6.8e + 1"

The result of this code is "6.8e + 1". As explained above, it indicates 6.8X101. The problem is, what if I don't know which form (pre-defined form or exponential form) is used to represent a number? You can use the toprecision () method.

Toprecision () method

The 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 ). For example,

VaR onumberobject = new number (68 );
Alert (onumberobject. toprecision (1); // output "7E + 1"

The task of this Code is to use a number to represent the number 68, the result is "7E + 1", in another form, that is, 70. Indeed, the toprecision () method rounds the logarithm. However, it is much easier to use two digits to represent 68:

VaR onumberobject = new number (68 );
Alert (onumberobject. toprecision (2); // output "68"

Of course, the output is "68", because this is the exact representation of the number. However, what if the specified number of digits is greater than the required number?

VaR onumberobject = new number (68 );
Alert (onumberobject. toprecision (3); // The output "68.0"

In this case, toprecision (3) is equivalent to tofixed (1) and outputs "68.0 ".

Both the tofixed (), toexponential (), and toprecision () Methods perform rounding to correctly represent a number with the correct number of decimal places.

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

See

For more information about the number object, visit the Javascript number object reference manual.

String object

A String object is an object representation of the original string type. It is created in the following way:

var oStringObject = new String("hello world");

Both the valueof () method and tostring () method of the string object return the original value of the string type:

Alert (ostringobject. valueof () = ostringobject. tostring (); // output "true"

If you run this code and the output is "true", it means these values are truly equal.

Note: A String object is one of the more complex reference types in ecmascript. Similarly, this section focuses on the basic functions of the string class. For more advanced functions, see the relevant sections of this tutorial or refer to the javascript string object reference manual.

Length attribute

The string object has the attribute length, which is the number of characters in the string:

VaR ostringobject = new string ("Hello World ");
Alert (ostringobject. Length); // output "11"

The output in this example is "11", that is, the number of characters in "Hello World. Note that even if the string contains double-byte characters (compared with ASCII characters, ASCII characters only occupy one byte), each character is counted as only one character.

Charat () and charcodeat () Methods

The string object also has a large number of methods.

First, the two methods charat () and charcodeat () access a single character in the string. Both methods have a parameter, that is, the location of the characters to be operated.

The charat () method returns a string containing characters at the specified position:

VaR ostringobject = new string ("Hello World ");
Alert (ostringobject. charat (1); // output "e"

In the string "Hello World", the character at position 1 is "E ". In the section "original ecmascript type", we have discussed that the first character is 0, and the second character is 1, and so on. Therefore, "e" is returned when charat (1) is called ".

If you want to get a character code instead of a character, you can call the charcodeat () method:

VaR ostringobject = new string ("Hello World ");
Alert (ostringobject. charcodeat (1); // The output "101"

This example outputs the character code of "101", that is, the lowercase letter "E.

Concat () method

Next we will use the Concat () method to connect one or more strings to the original values of the string object. This method returns the original string value, keeping the original string object unchanged:

VaR ostringobject = new string ("hello ");
VaR sresult = ostringobject. Concat ("world ");
Alert (sresult); // output "Hello World"
Alert (ostringobject); // output "hello"

In the above Code, "Hello world" is returned by calling the Concat () method, while the string object is still "hello ". For this reason, it is common to connect strings with the plus sign (+), because this form shows the true behavior from the logic:

VaR ostringobject = new string ("hello ");
VaR sresult = ostringobject + "world ";
Alert (sresult); // output "Hello World"
Alert (ostringobject); // output "hello"
Indexof () and lastindexof () Methods

So far, we have discussed how to connect strings and how to access a single character in strings. However, if you cannot determine whether a character exists in a string, what method should you call? You can call the indexof () and lastindexof () methods.

The indexof () and lastindexof () Methods return the position of the specified substring in another string. If no substring is found,-1 is returned.

The difference between the two methods is that the indexof () method retrieves strings starting from the beginning of a string (position 0), while the lastindexof () method () the method is to retrieve the substring from the end of the string. For example:

VaR ostringobject = new string ("Hello world! ");
Alert (ostringobject. indexof ("O"); output "4"
Alert (ostringobject. lastindexof ("O"); output "7"

Here, the first "O" string appears at location 4, that is, "O" in "hello"; the last "O" appears at location 7, that is, "world"
". If the string contains only one "O" string, the indexof () and lastindexof () Methods return the same location.

Localecompare () method

The next method is localecompare () to sort strings. This method has a parameter-the string to be compared and returns one of the following three values:

  • If the string object is placed before the string in the parameter in alphabetical order, a negative number is returned.
  • If the string object is equal to the string in the parameter, 0 is returned.
  • If the string object is placed after the string in the parameter in alphabetical order, a positive number is returned.

Note: If a negative number is returned,-1 is the most common one, but the actual return is determined by the implementation. If a positive number is returned, 1 is the most common, but the actual return is determined by the implementation.

Example:

VaR ostringobject = new string ("yellow ");
Alert (ostringobject. localecompare ("brick"); // output "1"
Alert (ostringobject. localecompare ("yellow"); // output "0"
Alert (ostringobject. localecompare ("Zoo"); // output "-1"

In this Code, the string "yellow" is compared with three values, that is, "brick", "yellow", and
"Zoo ". Localecompare () returns
1; "yellow" equals "yellow", so localecompare () returns 0; "Zoo" is located in "yellow"
Then, localecompare () returns-1. Once again, since the returned value is determined by the implementation, it is best to call
Localecompare () method:

var oStringObject1 = new String("yellow");
var oStringObject2 = new String("brick");

var iResult = sTestString.localeCompare("brick");

if(iResult < 0) {
alert(oStringObject1 + " comes before " + oStringObject2);
} else if (iResult > 0) {
alert(oStringObject1 + " comes after " + oStringObject2);
} else {
alert("The two strings are equal");
}

Using this structure ensures that the code runs correctly in all implementations.

Localecompare ()
The unique feature of the method is that the implementation region (locale, also referred to as the country/region and language) specifies the method of running this method. In the United States, the English language is ecmascript
In the standard language, localecompare () is case-sensitive, and upper-case letters are placed after lower-case letters in alphabetical order. However, this may not be the case in other regions.

Slice () and substring ()

Ecmascript provides two methods to create string values from substrings: slice () and
Substring (). The two methods return the substrings of the strings to be processed, both of which accept one or two parameters. The first parameter is the starting position of the substring to be obtained, and the second parameter (if you use
To obtain the position before the end of the substring (that is, the characters at the end of the substring are not included in the returned value ). If the second parameter is omitted, the end bit is the string length by default.

Like the Concat () method, the slice () and substring () methods do not change the value of the string object. They only return the original string value and keep the string object unchanged.

VaR ostringobject = new string ("Hello World ");
Alert (ostringobject. Slice ("3"); // output "lo world"
Alert (ostringobject. substring ("3"); // output "lo world"
Alert (ostringobject. Slice ("3, 7"); // output "lo w"
Alert (ostringobject. substring ("3, 7"); // output "lo w"

In this example, slice () and substring () have the same usage and return values. When only parameter 3 is specified, both methods return "Lo ".
World ", because the second" l "in" hello "is located at location 3. When there are two parameters "3" and "7", the values returned by both methods are "Lo
W "(the letter" O "in" world "is located on location 7, so it is not included in the result ).

Why are there two methods with identical functions? In fact, these two methods are not exactly the same, but they are slightly different when the parameters are negative.

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 ). For example:

VaR ostringobject = new string ("Hello World ");
Alert (ostringobject. Slice ("-3"); // output "rld"
Alert (ostringobject. substring ("-3"); // output "Hello World"
Alert (ostringobject. Slice ("3,-4"); // output "lo w"
Alert (ostringobject. substring ("3,-4"); // output "El"

This shows the main differences between slice () and substring () methods.

If the parameter is only-3, slice () returns "rld", and substring () returns "Hello World ". This is because for strings
"Hello World", slice ("-3") will be converted to slice ("8"), and substring ("-3") will be converted
Substring ("0 ").

Similarly, when parameters 3 and-4 are used, the difference is obvious. Slice () will be converted to slice (3, 7), same as the previous example, return "Lo
W ". The substring () method interprets two parameters as substring (3, 0), which is actually substring (0, 3), because
Substring () always uses a small number as the start position and a large number as the end position. Therefore, substring ("3,-4") returns
"El ". The last line of code is used to illustrate how to use these methods.

Tolowercase (), tolocalelowercase (), touppercase (), and tolocaleuppercase ()

The last method to be discussed involves case-sensitivity conversion. You can use either of the following four methods to perform case-insensitive conversions:

  • Tolowercase ()
  • Tolocalelowercase ()
  • Touppercase ()
  • Tolocaleuppercase ()

From the name, we can see their usage. The first two methods are used to convert strings into lowercase letters, and the last two methods are used to convert strings into uppercase letters.

The tolowercase () and touppercase () methods are original and implemented using the same method in Java. Lang. String as the prototype.

The tolocalelowercase () and tolocaleuppercase () methods are implemented based on
The localecompare () method is the same ). In many regions, region-specific methods are identical to common methods. However, there are several languages for Unicode
The case-sensitivity conversion applies specific rules (such as Turkish), so you must use a region-specific method to perform the correct conversion.

VaR ostringobject = new string ("Hello World ");
Alert (ostringobject. tolocaleuppercase (); // output "Hello World"
Alert (ostringobject. touppercase (); // output "Hello World"
Alert (ostringobject. tolocalelowercase (); // output "Hello World"
Alert (ostringobject. tolowercase (); // output "Hello World"

In this Code, touppercase () and tolocaleuppercase () both output "Hello
World ", tolowercase () and tolocalelowercase () both output" Hello
World ". Generally, if you do not know which encoding is used to run a language, it is safer to use a region-specific method.

Tip: Remember, all attributes and methods of string objects can be applied to the original values of string because they are pseudo objects.

Instanceof Operator

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 ". Ecmascript introduces another Java operator instanceof to solve this problem.

The instanceof operator is similar to the typeof operator and is used to identify the type of the object being processed. Unlike the typeof method, the instanceof method requires developers to explicitly confirm that the object is of a specific type. For example:

VaR ostringobject = new string ("Hello World ");
Alert (ostringobject instanceof string); // outputs "true"

This code asks "is the variable ostringobject A String object instance ?" Ostringobject is indeed a string
So the result is "true ". Although not as flexible as the typeof method, the typeof method returns "object"
In this case, the instanceof method is still very useful.

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.