JavaScript basic Wrapper type Introduction _javascript tips

Source: Internet
Author: User
Tags lowercase numeric value wrapper

To facilitate manipulation of basic type values, ECMAScript provides 3 special reference types: Boolean, number, and String. These types are similar to other reference types, but also have special behaviors corresponding to their respective base types. In fact, each time a base type value is read, the background creates an object of the corresponding base wrapper type, allowing you to invoke methods to manipulate the data.

A Basic wrapper Type Overview

var box = ' Mr Lee; '//define a string
var box2 = box.substring (2);//Truncate the first two-bit
alert (box2) of the string;//Output the new string


The variable box is a string type, and Box.substring (2) also indicates that it is an object (PS: Only the object will invoke the method), and finally assigns the processing result to Box2. ' Mr Lee ' is a string-type value that should not be an object and should not have its own method, such as:

Alert (' Mr Lee '. SUBSTRING (2));//directly by value to invoke method


1. Literal notation:

var box = ' Mr lee '/literal
box.name = ' lee '//invalid attribute
box.age = function () {//invalid method return
;
};
alert (box);//MR Lee
alert (box.substring (2));//. Lee
alert (typeof box);//string
alert (box.name);//undefined
alert (Box.age ());//Error


2.new operator notation:

var box = new String (' Mr Lee ');//new operator
box.name = ' Lee ';//valid property
Box.age = function () {//effective method return
100;
   };
alert (box);//MR Lee
alert (box.substring (2));//. Lee
alert (typeof box);//object
alert (box.name);//lee
alert (Box.age ());//100


The above literal declarations and the new operator declarations are a good demonstration of the difference between them. But it is certain that it is possible to use its built-in methods regardless of the literal form or the new operator form. And the Boolean and number attributes are the same as String, three types can be the base wrapper type.

PS: When you use the new operator to create the above three types of objects, you can add properties and methods to yourself, but we recommend that you do not do so because it causes the fundamental type or reference type value to be unclear.

Two Boolean type

A Boolean type does not have a specific property or method.

Three Number Type

The number type has some static properties (properties called directly through number without the new operator) and methods.

Number static Property

Method of Number Object

var box = 1000.789;
Alert (box.tostring ());//Convert to string, parameter can be converted into
alert (box.tolocalestring ());//local form, 1,000.789
alert (box.tofixed (2)); /decimal point reservation, 1000.78
alert (box.toexponential ());//exponential form, the participant retains the decimal point
alert (Box.toprecision (3));/index or Point form, and the argument retains the decimal point

Four String type

The String type contains three properties and a large number of available built-in methods.

String Object Properties

String also contains common methods for objects, such as valueof (), tolocalestring (), and toString () methods, but these methods return the base value of the string.

Character method

var box = ' Mr.Lee ';
Alert (Box.charat (1));//r
alert (box.charcodeat (1));//114
alert (box[1));//r, intercept by array

PS:BOX[1] in IE browser will display undefined, so use caution.

String manipulation methods

var box = ' Mr.Lee ';
Alert (Box.concat (' is ', ' Teacher ', '! ')); /mr.lee is Teacher!
Alert (Box.slice (3)),//lee
alert (Box.slice (3,5)),//le
alert (box.substring (3)),//lee
alert ( Box.substring (3,5)),//le
alert (BOX.SUBSTR (3)),//lee
alert (box.substr (3,5)),//lee


var box = ' Mr.Lee ';
Alert (Box.slice ( -3));//lee,6+ (-3) = 3-bit start
alert (box.substring ( -3));//mr.lee negative number returns all
alert (BOX.SUBSTR (-3)) //lee,6+ (-3) = 3 bit start


var box = ' Mr.Lee ';
Alert (Box.slice (3,-1)),//le 6+ ( -1) =5, (3,5)
alert (box.substring (3,-1)),//MR. The second parameter is negative, direct to 0, and the method will bring the smaller number forward, (0,3)
Alert (BOX.SUBSTR (3,-1));//' The second parameter is negative, direct turn 0, (3,0)

Ps:ie's JavaScript implementation has a problem with the process of passing a negative value to the substr () method, which returns the original string, which should be remembered when used.

String Position method

var box = ' Mr.Lee is Lee ';
Alert (Box.indexof (' l '));//3
alert (box.indexof (' l ', 5));//10
alert (box.lastindexof (' l '));//10
alert ( Box.lastindexof (' L ', 5);//3, searching forward from the specified position

PS: If the desired string is not found, return-1.

Example: Find all of the L.

var box = ' Mr.Lee is Lee ';//A String containing two L
(var boxarr = [];//storing an L-position array
var pos = box.indexof (' l '); get first L position 
   
    while (pos >-1) {//If position is greater than-1, there is also
an L boxarr.push (POS);//Add to array
pos = Box.indexof (' L ', pos + 1); The current bit of the new assignment pos Set
}
alert (Boxarr);//Output
   

Capitalization conversion method

var box = ' Mr.Lee is Lee ';
Alert (Box.tolowercase ());//All lowercase
alert (box.touppercase ());//All Caps
alert (box.tolocalelowercase ()
); Alert (Box.tolocaleuppercase ());

PS: Only a few languages (such as Turkish) have local-specific capitalization, and generally, the localization effect is consistent.

Pattern matching methods for strings

The application of regular expressions in strings is discussed in detail in the previous chapters and is not discussed here. The above match (), replace (), Serach (), split () can also be used in the normal string.

var box = ' Mr.Lee is Lee ';
Alert (Box.match (' l '));//Find L, return l otherwise return null
alert (box.search (' l '));//Find the position of L, and indexOf type
alert (Box.replace (' L ', ' Q ')//replace L
with Q alert (Box.split ("));//split into strings with spaces

Other methods

alert (string.fromcharcode);//l, output ASCII-code corresponding value

Localecompare (str1,str2) Method: compare two strings and return one of the following values;

1. Returns a negative number if the string should precede the string parameter in the alphabet. (Majority-1)
2. Returns 0 if the string is equal to a string parameter.
3. Returns a positive number if the string should be in the string argument from the schedule. (most 1)

[Task]var box = ' Lee ';
Alert (Box.localecompare (' apple '));//1
alert (box.localecompare (' Lee '));//0
alert Box.localecompare (' Zoo '));//-1

HTML methods

Above is through JS to generate an HTML tag, according to experience, nothing much use, do an understanding.

var box = ' Lee ';
Alert (Box.link (' http://www.jb51.net '));//Hyperlink

Tutorial content from Li Tinghui teacher JavaScript Tutorial

The following are the articles organized by other netizens:

Overview of a basic packaging type

In fact, each time a base type value is read, the background creates an object of the corresponding base wrapper type, which enables you to invoke methods to manipulate the data;

  var box = ' Mr.Lee ';          Defines a string literal;  
  var box2 = box.substring (2);    Truncate the top two bits of the string;
  Console.log (box2);          Output a new string; =>. Lee;
  The variable box is a string type, and Box.substring (2) also indicates that it is an object (only objects will invoke the method);
  Console.log (' Mr.Lee '. SUBSTRING (3));  Call method directly via string value =>lee;

The main difference between a reference type and a basic wrapper type is the lifetime of the object;
An object of the base wrapper type that is automatically created, exists only in the execution moment of a line of code, and is immediately destroyed;
This means that we cannot add properties and methods to the base type values at run time;

    var s1 = ' Some text ';                //=> var S1 = new String (' some text ');
    var s2 = s1.substring (5);            => var s2 = s1.substring (5);
                                          //S1 = null; Destroy this instance; the background automatically executes;
1. Literal notation

  var box = ' Mr.Lee ';         literal amount;
  Box.name = ' Lee ';          Invalid attribute;
  Box.age = function () {        //invalid method;
    return;
  };
  Console.log (Box.substring (3));    =>lee;
  Console.log (typeof box);       =>string;
  Console.log (box.name);        =>undefined;
  Console.lgo (Box.age ());       => error;

2.new operator notation

  var box = new String (' Mr.Lee ');
  Box.name = ' Lee ';
  Box.age = function () {return
    ;
  };
  Console.log (Box.substring (3));    =>lee;
  Console.log (typeof box);      =>object;
  Console.log (box.name);        =>lee;
  Console.lgo (Box.age ());        =>100;

The above literal declaration and the new operator declaration well show the difference between them;
However, both literal and new operators can use its built-in method (substring);

Two Boolean types

A Boolean type has no specific properties or methods;

Three number types

The number type has some static properties (called directly by number without the new operator) and method;

Static properties of 1.Number objects

Max_value represents the maximum number;
Min_value represents the minimum value;
NaN non-numeric;
Negative-infinity negative infinity, the overflow returns the value;
Positive_infinity Infinity, the overflow returns the value;
Prototype prototype for adding new attributes and methods;

Methods of 2.Number objects

ToString () converts a numeric value into a string, and can be converted into a system;
toLocaleString () converts a string according to the local number format;
ToFixed () retains the number of digits after the decimal point and converts it to a string;
Toexponential () The number is expressed in exponential form;
Toprecision () Exponential form or point form represents a number;

Four string types

The string type contains three attributes and a large number of available built-in methods;

1.String Object Properties

Length returns the character lengths of the string;
Constructor returns the function that created the string object;
Prototype by adding properties and methods to extend the string definition; 2.String Object Character method
CHARAT (n) returns the character at the specified index position;
charCodeAt (n) the encoding of the character that returns the specified index position in Unicode encoding;
var box = ' Mr.Lee ';
Console.log (Box.charat (1)); =>r;
Console.log (Box.charcodeat (1)); =>114;
     Console.log (box[1])                         //=>r; intercept by array; 3.String Object string Manipulation method

Concat (STR1...STR2) concatenates string arguments to the string that invokes the method;
Slice (n,m) returns a string between the string position n through m;
SUBSTRING (n,m) ditto;
SUBSTR (n,m) returns the M string at the beginning of the string position n;
var box = ' Mr.Lee ';
Console.log (Box.concat (' ok! ')); =>mr.lee ok!;
Console.log (Box.slice (3)); =>lee; (intercepts all characters starting from index 3);
Console.log (box.substring (3,5)); =>le; (the character that intercepts index 3 through index 5); 4.String Object String Position method

IndexOf (str,n) searches backwards from index n for the first STR and returns the index value of the search;
LastIndexOf (str,n) searches the first str from index n and returns the index value of the search;
var box = ' Mr.Lee is Lee ';
Console.log (Box.indexof (' L ')); =>3; (the index value of the first l, previously searched backwards, is 3);
Console.log (Box.lastindexof (' L ')); =>10; (the index value of the first l, which is searched from the back forward, is 10);
Console.log (Box.indexof (' L ', 5)); =>10; (the index value of the first l that is searched backwards from the 5th one is 10);
Returns 1 if the string to search is not found;

Find all the L;
var box = ' Mr.Lee is Lee ';
var boxarr = []; An array that holds l;
var pos = box.indexof (' L '); Gets the position of the first L;
while (pos>-1) {//If position is greater than-1, there is also an L;
Boxarr.push (POS); Adds the found index to the array;
pos = Box.indexof (' L ', pos+1); Re-assign the current position of the POS;
}
Console.log (Boxarr); [3,10]

Trim () method
ECMASCRIPT5 defines the trim () method for all strings, which creates a copy of the string, deletes all the spaces of the front and suffix, and returns the result;
var str = ' Hello world ';
var trimstr = Str.trim ();
Console.log (TRIMSTR);    =>hello World;             Console.log (str); => Hello World 24//since trim () returns a copy of the string, the front and suffix spaces in the original string remain unchanged; 5.String Object string Capitalization conversion method
toLowerCase (str) converts the string to lowercase;
toUpperCase (str) converts the string to uppercase;
toLocaleLowerCase (str) converts the string to all lowercase and localized;
toLocaleLowerCase (str) converts a string to uppercase and localized; a pattern-matching method for 6.String object strings

The specific use method is introduced in the regular;
Match (pattern) returns the substring or null in pattern; Same as pattern.exec (str);
Replace (pattern,replacement) replaces pattern with replacement;
Search (pattern) returns the pattern start position in the string;
Split (pattern) returns an array of strings that are split by the specified pattern;
var box = ' Mr.Lee is Lee ';
var p =/l/g; To open the global regular;
Console.log (Box.match (p)); =>[l,l];
Console.log (Box.search (p)); =>3;
Console.log (Box.replace (P, ' Q ')); =>mr.qee is Qee;
Console.log (Box.split (')); =>[' Mr.Lee ', ' is ', ' Lee '];7.string object other methods
fromCharCode (ASCII) static method, output ASCII code corresponding value;
Localecompare (STR1,STR2) compares two strings and returns the corresponding values; 8.String Object HTML method
The use of JS to generate an HTML tag, is not very useful;
var box = "Lee";
Console.log (Box.link (' www.baidu.com ')); <a href= "www.baidu.com" >Lee</a>;

Five Summary
Because of the basic packaging type, the basic type value in JS can be accessed as an object;
Basic type characteristics:
1. Each wrapper type is mapped to the base type with the same name;
2. When accessing basic type values in read mode, an object of the corresponding basic wrapper type is created, which facilitates data manipulation;
3. Once the statement of the operation base type value is executed, the newly created wrapper object is destroyed immediately;

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.