JavaScript Advanced Tutorial 5.6 Basic Packaging Type (detail) _javascript tips

Source: Internet
Author: User
Tags instance method locale numeric value trim wrapper

To facilitate operation of basic type values, ECMAScript also provides 3 special reference types: boolean,number,string.

In fact, whenever a basic type value is read, the background is to create an object of the corresponding base wrapper type so that we can call some methods to manipulate the data.

var s1= "some text";
  var s2=s1.substring (2);
  Console.log (s2);//me text

In this example, S1 contains a string that is the base type value. The second line invokes the S1 subsstring () method and saves the returned results in S2.

When the second line of code accesses S1, the access procedure is in a read mode, which is to read the value of the string from memory. While accessing a string in read mode, the background automatically completes the following processing.

(1) Create an instance of string type;

(2) Invoking the specified method on the instance;

(3) Destroy this instance.

You can think of the above three steps as executing the following code:

var s1=new String ("some text");
  var s2=s1.substring (2);
  S1=null;
  Console.log (s2);//me text

After this process, the basic string value becomes the same as the object. The above three steps also apply to Boolean and numeric values corresponding to the Boolean and number types respectively.

The main difference between a reference type and a base wrapper type is the lifetime of the object.

An instance of a reference type created using the new operator, is saved in memory together before the execution flow leaves the current scope. The object of the base wrapper type that is automatically created, exists only in the execution of one line of code and is immediately destroyed. This means that we cannot add properties and methods to the base type at run time.

var s1= "some text";
  S1.color= "Red";
  Console.log (S1.color);//undefined

The problem is that the string object created in the second line has been destroyed when it executes the third line of code. The third line of code creates its own string object, which has no color property.

Calling typeof on an instance of the base wrapper type returns "Object", and all objects of the base wrapper type are converted to the Boolean value true.

The object constructor, like the factory method, returns an instance of the corresponding base wrapper type based on the type of the passed-in value.

var obj=new Object ("some text");
  Console.log (obj instanceof String);//true

Passing the string to the object constructor creates an instance of string, and an incoming numeric parameter gets an instance of number, and the passed-in boolean parameter gets an instance of the Boolean.

Note that using new to invoke the constructor of the base wrapper type is not the same as a transition function that invokes the same name directly.

var value= ";
  " var number=number (value);//transition function
  Console.log (typeof number);//number
  var obj=new number (value);//Constructor
  Console.log (typeof obj);//object

In this example, the variable number holds the value 25 of the base type, and the variable obj holds an instance of number.

5.6.1 Boolean type

A Boolean type is a reference type that corresponds to a Boolean value. To create a Boolean object, you can call the Boolean constructor and pass in a true or False value as follows.

var booleanobject=new Boolean (True);

An instance of a Boolean type overrides the ValueOf () method, returns the base type value TRUE or FALSE, overrides the ToString () method, and returns the string "true" and "false". However, the Boolean object is not very useful in ECMAScript Because it often makes people misunderstand.

One of the most common problems is the use of Boolean objects in Boolean expressions.

var falseobject=new Boolean (false);
  var result=falseobject&&true;
  Console.log (result);//true
  var falsevalue=false;
  result=falsevalue&&true;
  Console.log (result);//false

In this example, a Boolean object is created with the value false. Then the object is constructed with the base type value true for the logic and expression. This line of code in the example is for falseobject rather than its value (false) evaluated. All objects in a Boolean expression are converted to true, so the Falseobject object represents true in a Boolean expression.

There are two differences between the base type and the Boolean value of the reference type: First, the TypeOf action returns "Boolean" to the base type, and the reference type returns "Object". Second, because a Boolean object is an instance of a Boolean type, So testing a Boolean object with the instanceof operator returns True, while a Boolean value that tests the base type returns FALSE.

Console.log (typeof falseobject);//object
  Console.log (typeof falsevalue);//boolean Console.log
  ( Falseobject instanceof Boolean);//true
  Console.log (Falsevalue instanceof Boolean);//false

5.6.2 Number Type

Number is a reference type that corresponds to a numeric value. To create a numbers object, you can pass the corresponding number to it when you call the # constructor.

var numberobject=new number (a);
  Console.log (typeof Numberobject);//object

As with the Boolean type, the number type also overrides the valueof (), tolocalestring (), and ToString () methods.

The overridden valueof () method returns a numeric value of the base type of the object's shell, while the other two returns a numeric value in the form of a string.

You can pass a parameter that represents the cardinality for the ToString () method, telling it to return a string form of a few binary values.

var num=10;
  Console.log (Num.tostring ());//10
  Console.log (num.tostring (2));//1010
  Console.log (num.tostring (8));//12
  Console.log (num.tostring);//10
  Console.log (num.tostring);//a

In addition to inherited methods, the number type also provides methods for formatting numeric values into strings.

where the ToFixed () method returns a string representation of a numeric value, according to the specified decimal bit.

var num=10;
Console.log (num.tofixed (2));//10.00

This gives the tofixed () method A value of 2, which means displaying several decimal places. Fill the necessary decimal digits with 0.

If the numeric value itself contains more decimal places than specified, the value close to the specified maximum number of digits is rounded.

var num=10.007;
  Console.log (num.tofixed (2));//10.01

An attribute that can be rounded automatically, makes the tofixed () method a good fit for handling currency values. However, it is important to note that the rounding rules that are set for this method by different browsers may vary. In the case of tofixed () passed in 0, IE8 and previous versions could not be rounded properly in {(-0.94), -0.5],[0.5,0.94)}. For this range of values, IE returns 0 instead of-1 or 1; Other browsers can return the correct values. IE9 fixed the problem.

Alternatively, the method that can be used to format a numeric value is toexponential (), which returns a string representation of the numeric value in exponential notation (also known as e notation). As with the tofixed () method, toexponential () also receives a parameter, Also, this parameter is also the number of decimal places in the specified output result.

var num=10;
  Console.log (num.toexponential (1));//1.0e+1

For a numeric value, the Toprecision () method may return a fixed size (fixed) format, or it may return a specified (exponential) format; This method receives a parameter that represents the digits of all digits of a numeric value ( Does not include the exponent part).

var num=99;
  Console.log (Num.toprecision (1));//1e+2
  Console.log (num.toprecision (2));//99
  Console.log ( Num.toprecision (3));//99.0

The second line is a number to represent 99, the third row is represented by two digits, and line fourth is represented by a three-digit number.

In fact, toprecision () determines whether to call tofixed () or call toexponential () based on the numeric value to be processed, and these three methods can be rounded up or down to represent values with the correct decimal digits in the most accurate form.

The Toprecision () method can represent 1 to 21 decimal places.

It is still not recommended to instantiate the number type directly. Specifically, the results are completely different when you use the TypeOf and instanceof operators to test the values of the base type and the reference type.

var numberobject=new number (a);
  var numbervalue=10;
  Console.log (typeof numberobject);//object
  Console.log (typeof numbervalue);//number Console.log
  ( Numberobject instanceof number);//true
  Console.log (numbervalue instanceof number);//false

When you use the TypeOf operator to test the base type numeric value, you always return "number", and when you test the numbers object, you return "object". Similarly, the number object is an instance of type A and the numeric value of the base type is not.

5.6.3 String Type

The string type is the object wrapper type of the string, which can be created as follows by using the string constructor.

var stringobject=new String ("Hello World");

The method of a string object can also be accessed in all basic string values. Where the inherited valueof (), the toloalestring (), and the ToString () method return the base string value represented by the object.

Each instance of string has a length property that indicates that the string contains more than one character.

var stringvalue= "Hello World";
  Console.log (stringvalue.length);

It should be noted that each character is still counted as a character, even if the string contains double-byte characters (not an ASCII character that occupies a byte).

1. Character method

Two methods for accessing specific characters in a string are: CharAt () and charCodeAt (). Both methods receive an argument, which is based on a 0 character position.

The CharAt () method returns the character of the given position in the form of one-character string.

If you want to get not a character but a character encoding, you need to use charCodeAt ().

ECMAScript also defines another way to access individual characters. In browsers that support this method, you can use square brackets plus a numeric index to access specific characters in a string.

var stringvalue= "Hello World";
  Console.log (stringvalue[1]);//e

The syntax for accessing individual characters using square brackets notation is supported by all versions of IE8 and Ff,safari,chrome and opera. If this syntax is used in IE7 and earlier versions, the undefined value is returned.

2. String Manipulation method

Concat (), which is used to concatenate one or more strings to return a new string that is stitched together.

var stringvalue= "Hello";
  var result=stringvalue.concat ("World");
  Console.log (result);//helloworld
  Console.log (stringvalue);//hello

Concat () returns a concatenation string that does not change the value of the original array. It can accept any number of parameters, that is, you can stitch any number of strings through it.

var stringvalue= "Hello";
  var result=stringvalue.concat ("World", "!")
  Console.log (result);//hellowworld!
  Console.log (stringvalue);//hello

Although Concat () is a method specifically used to stitch strings, the practice uses more of the plus sign operator (+). Moreover, using the plus operator is easier in most cases than using the Concat () method (especially if you are stitching multiple strings).

ECMAScript also provides three methods for creating new strings based on substrings: Slice (), substr (), and substring ().

All three methods return a substring of the manipulated string, and all accept one or two arguments. The first parameter specifies the start position of the substring, and the second parameter (in the case specified) indicates where the substring ends. Slice () and substring () The second parameter specifies the position after the last character of the substring. The second parameter of substr () specifies the number of characters returned. If the method is not passed a second argument, the length of the string is used as the end position. As with Concat () method, slice (), SUBSTR () and substring () also do not modify the values of the string itself-they simply return a string value of the base type and have no effect on the original string.

var stringvalue= "Hello World";
  Console.log (Stringvalue.slice (3)),//lo World
  Console.log (stringvalue.substring (3)),//lo
  World Console.log (STRINGVALUE.SUBSTR (3));//lo World
  Console.log (Stringvalue.slice (3,7));//lo W
  Console.log ( Stringvalue.substring (3,7));//lo W
  Console.log (Stringvalue.substr (3,7));//lo Worl

SUBSTR () returns "Lo Worl" because its second argument specifies the number of characters to return.

In cases where the arguments passed to these methods are negative, the slice () method adds the Passed-in negative value to the length of the string, and the substr () method adds the negative first argument to the length of the string, and the negative second argument to 0. Finally, substring () Method converts all negative parameters to 0.

var stringvalue= "Hello World";
  Console.log (Stringvalue.slice ( -3));//rld
  Console.log (stringvalue.substring ( -3));//hello
  World Console.log (Stringvalue.substr ( -3));//rld
  Console.log (Stringvalue.slice (3,-4));//lo W
  Console.log ( Stringvalue.substring (3,-4));//hel
  Console.log (Stringvalue.substr (3,-4));//(Empty string)

Note: The JavaScript implementation of IE is problematic when handling negative values to the substr () method, which returns the original string. IE9 fixed the problem.

When the second argument is a negative value, the the behavior of three methods is different. The slice () method converts the second argument to the 7,substring () method converts the second argument to 0, and because this method takes the smaller number as the starting position, the larger number as the ending position. substr () The second argument is also converted to 0, which means that a string containing 0 characters is returned, which is an empty string.

3. String Position method

There are two ways to find substrings from a string: IndexOf () and LastIndexOf (). Both methods search for a given substring from a string, and then return the position of the substring (1 if the string is not found).

The IndexOf () method searches the substring backwards from the beginning of the string, and the LastIndexOf () method searches the substring forward from the end of the string.

var stringvalue= "Hello World";
  Console.log (Stringvalue.indexof ("O"));//4
  Console.log (Stringvalue.lastindexof ("O"));//7

If "O" appears only once in this string, then indexof () and LastIndexOf () return the same position value.

Both methods can receive an optional second argument that indicates where to start the search from within the string. In other words, indexOf () searches backwards from the position specified by the parameter, ignoring all characters before the position, and LastIndexOf () searches forward from the specified location. All characters after this position are ignored.

var stringvalue= "Hello World";
  Console.log (Stringvalue.indexof ("O"), 6);//4 6
  Console.log (Stringvalue.indexof ("O", 6));//7
  Console.log ( Stringvalue.lastindexof ("O", 6);//4
var stringvalue= "Lorem ipsum dolor sit amet, consectetur adipisicing";
  var positions=new Array ();
  var pos=stringvalue.indexof ("E");
  while (pos>-1) {
    positions.push (POS);
    Pos=stringvalue.indexof ("E", pos+1);
  }
  Console.log (positions);//[3,24,32,35,52]

This example iterates through a long string by increasing the indexof () method to start the lookup. Outside the loop, the initial position of "E" in the string is first found, and after the loop, the indexof () is passed the previous position plus 1. In this way, Ensures that each search starts at the end of the substring that was last found. Each search return location is saved in the array positions in turn for future use.

4.trim () method

ECMAScript 5 defines the trim () method for all strings. This method creates a copy of the string, deletes all the spaces of the front and suffix, and then returns the result.

var stringvalue= "  Hello World  ";
  var Trimmedstringvalue=stringvalue.trim ();
  Console.log (stringvalue)/  Hello World  
  console.log (trimmedstringvalue),//hello World

Because Trim () returns a copy of the string, the front and suffix spaces in the original string remain unchanged. Browsers that support this approach have Ie9+,ff3.5+,safari5+,opera 10.5+ and chrome. In addition, Ff3.5+,safari 5+ And the chrome 8+ also supports non-standard trimleft () and TrimRight () methods, which are used to remove spaces at the beginning and end of a string, respectively.

5. String capitalization conversion method

There are 4 methods in ECMAScript that involve string capitalization conversions: toLowerCase (), toLocaleLowerCase (), toUpperCase (), and toLocaleUpperCase ().

var stringvalue= "Hello World";
  Console.log (Stringvalue.tolocaleuppercase ());//hello World
  Console.log (Stringvalue.touppercase ());//hello World
  Console.log (Stringvalue.tolocalelowercase ()),//hello World
  Console.log (Stringvalue.tolowercase ( );//hello World

In general, it is safer to use a locale-specific approach without knowing what locale your code will run in.

6. Pattern matching method of string

The string type defines several methods for matching patterns in a string. The first method is match (), which is called on the string, essentially the same as the Exec () method that invokes RegExp. The match () method accepts only one parameter, or a regular expression, Or it's a RegExp object.

var text= "Cat,bat,sat,fat";
  var pattern=/.at/;
  Same as Pattern.exec (text)
  var matches=text.match (pattern);
  Console.log (Matches.index);//0
  Console.log (matches[0));//cat Console.log
  (pattern.lastindex);//0

The match () method in this example returns an array; if you call the Exec () method of the RegExp object and pass the string in this example as a parameter, you also get the same array: the first item in the array is a string that matches the entire pattern, and each subsequent item (if any) A string that matches the capturing group in the regular expression is saved.

Another method for finding patterns is search (). The unique parameter of this method is the same as the parameter of the match () method: a regular expression specified by a string or RegExp object. The search () method returns the index of the first occurrence in the string, and if no match is found, Returns-1. Also, the search () method always looks backward from the beginning of the string.

var text= "Cat,bat,sat,fat";
  var pos=text.search (/at/);
  Console.log (POS);//1

To simplify the substitution of substrings, ECMAScript provides the replace () method. This method takes two parameters: the first argument can be a RegExp object or a string (this string will not be converted to a regular expression). The second argument can be a string or a function. If the first argument is a string, only the first substring is replaced. The only way to replace all substrings is to provide a regular expression and specify the Global (g) flag.

var text= "Cat,bat,sat,fat";
  var result=text.replace ("At", "ond");
  Console.log (result);//cond,bat,sat,fat
  result=text.replace (/at/g, "ond");//cond,bond,sond,fond

After that, by modifying the first argument to a regular expression with a global flag, all "at" is replaced with "ond".

If the second argument is a string, you can also use some special sequence of characters to insert the value from the regular expression operation into the result string.

The following is a list of these special character sequences provided by ECMAScript.

Character sequence Replace text
$$ $
$& A substring that matches the entire pattern. The same value as the Regexp.lastmatch
$' The substring before the matched substring. The same value as the Regexp.leftcontext
$` The substring after the matched substring. The same value as the Regexp.rightcontext
$n Matches the substring of the nth capturing group, where n equals 0~9. For example, $ is a substring that matches the first capturing group, and $ is a substring that matches the second capturing group. And so on. If no capturing group is defined in the regular expression, an empty string is used
$nn Matches the substring of the first NN capturing group, where NN equals 01~99. For example, $01 is a substring that matches the number one capturing group, $02 is the substring that matches the second capturing group, and so on. If no capturing group is defined in the regular expression, an empty string is used

These special sequences of characters allow you to use the contents of the most recent matching result.

var text= "Cat,bat,sat,fat";
  Result=text.replace (/(. at)/g, "Word ($)");
  Console.log (result);//word (cat), Word (BAT), Word (Sat), Word (FAT)

In this case, each word ending with ". At" is replaced with the result that word is followed by a pair of parentheses, and the parentheses are the words that are replaced by the character sequence.

The second parameter of the replace () method can also be a function. In the case of only one match (that is, a string that matches the pattern), 3 functions are passed to the function: the match of the pattern, the pattern match at the position of the string, and the original string. In the case where more than one capturing group is defined in the regular expression, The arguments passed to the function are the matches of the pattern, the first captures the match for the group, and the second captures the match for the group ..., but the last two parameters are still the position of the pattern match in the string and the original string. This function should return a string, Indicates that a match that should be replaced uses a function as the second parameter of the replace () method to achieve finer substitution operations.

function Htmlescape (text) {return
    text.replace (/[<>) &]/g,function (match,pos,originaltext) {
      Switch (match) {case
        ' < ': return
          ' < ';
        Case ">": Return
          ">";
        Case "&": Return
          "&";
        Case "\" ": Return
          " "";}}
    );
  Console.log (Htmlescape ("<p class=\" greeting\ ">hello world!</p>*"))//<p class= "greeting" >Hello world!</p>*

Here, we define the function htmlescape () for inserting HTML code, which can escape 4 characters: less than, greater than, and number, and double quotes. The easiest way to implement this escape is to use regular expressions to find these characters, It then defines a function that can return a specific HTML instance for each matching character.

The last method associated with pattern matching is split (), this method splits a string into multiple substrings based on the specified delimiter, and places the result in an array. The delimiter can be either a string or a RegExp object (this method does not regard the string as a regular expression). The split () method accepts an optional second argument that specifies the size of the array to ensure that the returned array does not exceed the established size.

var colortext= "Red,blue,green,yellow";
  var color1=colortext.split (",");
  Console.log (Color1);//["Red", "Blue", "green", "yellow"]
  var color2=colortext.split (",", 2);
  Console.log (COLOR2);//["Red", "blue"]
  var color3=colortext.split (/[^\,]+/);
  Console.log (COLOR3);//[",", ",", ",", "," "," "," "

In the last call to the array returned by split (), the first and last items are two empty strings. This is because the delimiter specified through the regular expression appears at the beginning of the string (that is, the substring "red") and the end (that is, the substring "yellow").

The support for split () positive expressions varies by browser. Although there is no difference between simple patterns, matching behavior is not the same for patterns that do not find matches and have capturing groups. Here are some of the differences in perception.

IE8 and previous versions ignore capturing groups. IE9 can correctly include capturing groups in the results.

FF3.6 and previous versions include an empty string in the result array when a match is not found in the capturing group; ECMA-262 A capturing group that does not have a match should be represented in the result array in undefined.

There are other subtle differences in the use of capturing groups in regular expressions.

7.localeCompare () method

This method compares two strings and returns one of the following values:

If the string should precede the string parameter in the alphabet, it returns a negative number (in most cases-1, depending on the implementation)

Returns 0 if the string is equal to a string parameter.

If the string should be in the alphabet after the string parameter, return a positive number (in most cases 1, the exact value will also depend on the implementation)

var stringvalue= "Yellow";
  Console.log (Stringvalue.localecompare ("Brick"));//1
  Console.log (Stringvalue.localecompare ("yellow"));//0
  Console.log (Stringvalue.localecompare ("Zoo"));//-1

Because the value returned by Localecompare () depends on the implementation, it is best to use this method as shown in the following example.

function Determineorder (value) {
    var result=stringvalue.localecompare (value);
    if (result<0) {
      Console.log ("The string ' yellow ' comes before the string '" +value+ '. ");
    } else if (result>0) {
      Console.log ("The string ' yellow ' comes after the string '" +value+ '. ");
    } else{
      Console.log ("The string ' yellow ' is equal to the string '" +value+ ");
    }
  Determineorder ("Brick");
  Determineorder ("yellow");
  Determineorder ("Zoo");

8.fromCharCode () method

In addition, the string constructor has a static method: fromCharCode (). The task of this method is to receive one or more character encodings and then convert them to a string. In essence, this method performs the opposite operation with the instance method charCodeAt ().

The above is a small part of the description of the JavaScript Advanced Tutorial 5.6 of the basic packaging type (detailed), I hope you like.

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.