Basic javascript packaging type introduction _ javascript skills

Source: Internet
Author: User
This article mainly introduces the basic packaging types of javascript. JS provides three special reference types to facilitate basic operation: BooleanNumber and String, for more information about the basic type values, ECMAScript provides three special reference types: Boolean, Number, and String. These types are similar to other reference types, but they also have special behaviors corresponding to their basic types. In fact, every time you read a basic type value, the background will create a corresponding basic packaging type object, so that you can call some methods to operate on the data.

1. Overview of basic packaging types

Var box = 'Mr. Lee '; // define a string var box2 = box. substring (2); // cut off the first two alert (box2) strings; // output the new string


The variable box is a string type, while box. substring (2) indicates that it is an object (PS: only the object can call the method). Finally, the processing result is assigned to box2. 'Mr. Lil' is a string type value. it should not be an object, but should not have its own method, for example:

Alert ('Mr. Lil'. substring (2); // call the method directly by using the value


1. literal writing:

Var box = 'Mr. lee '; // literal box. name = 'Lil'; // invalid attribute box. age = function () {// The return 100;}; alert (box); // Mr. leealert (box. substring (2 ));//. leealert (typeof box); // stringalert (box. name); // undefinedalert (box. age (); // error


2. new operator syntax:

Var box = new String ('Mr. lee '); // new operator box. name = 'Lil'; // valid attribute box. age = function () {// valid method return 100 ;}; alert (box); // Mr. leealert (box. substring (2 ));//. leealert (typeof box); // objectalert (box. name); // Leealert (box. age (); // 100.


The preceding literal declaration and the new operator declaration demonstrate the differences between them. However, it must be certain that the built-in method can be used regardless of the literal form or the new operator form. In addition, the Boolean and Number features are the same as those of String. The three types can be basic packaging types.

PS: When you use the new operator to create the above three types of objects, you can add attributes and methods for yourself, but we do not recommend using these methods, this will make it hard to tell whether it is a basic type value or a reference type value.

II. Boolean type

The Boolean type does not have specific attributes or methods.

III. Number type

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

Number static attribute

Number object method

Var box= 1000.789; alert (box. toString (); // converts a parameter to a string. you can convert the input value to alert (box. toLocaleString (); // Local format, 1,000.789 alert (box. toFixed (2); // reserved decimal point, 1000.78 alert (box. toExponential (); // exponential form, passing parameters will retain the decimal point alert (box. toPrecision (3); // exponential or vertex form, passing parameters to retain the decimal point

IV. String type

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

String object attributes

String also contains common methods of the object, such as the valueOf (), toLocaleString (), and toString () methods, but these methods all return the basic value of the String.

Character method

Var box = 'Mr. lee '; alert (box. charAt (1); // ralert (box. charCodeAt (1); // 114 alert (box [1]); // r, captured in array mode

PS: box [1] will display undefined in IE browser, so be careful when using it.

String operation method

Var box = 'Mr. Lil'; alert (box. concat ('is', 'teacher ','! '); // Mr. Lee is Teacher! Alert (box. slice (3); // Leealert (box. slice (3, 5); // Lealert (box. substring (3); // Leealert (box. substring (3, 5); // Lealert (box. substr (3); // Leealert (box. substr (3, 5); // Leevar box = 'Mr. lee '; alert (box. slice (-3); // Lee, 6 + (-3) = 3 bits starting alert (box. substring (-3); // Mr. negative Lee 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, which is directly converted to 0, and the method will advance the smaller number, () alert (box. substr (3,-1); // ''The second parameter is negative and is directly converted to 0)

PS: the JavaScript implementation of IE has a problem when the negative value is passed to the substr () method. it will return the original string, which should be remembered during use.

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, search forward from the specified position

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

Example: find all L values.

Var box = 'Mr. lee is Lee '; // string containing two L var boxarr = []; // array storing the L position var pos = box. indexOf ('L'); // first obtain the position of the first L while (pos>-1) {// if the position is greater than-1, Lboxarr exists. push (pos); // add to array pos = box. indexOf ('L', pos + 1); // returns the current position of the pos} alert (boxarr); // output

Case sensitivity conversion method

Var box = 'Mr. lee is Lee '; alert (box. toLowerCase (); // All lowercase alert (box. toUpperCase (); // all uppercase alert (box. toLocaleLowerCase (); alert (box. toLocaleUpperCase ());

PS: only a few languages (such as Turkish) are local-specific and case-sensitive. Generally, the localization effect is consistent.

String pattern matching method

The application of regular expressions in strings has been discussed in detail in the previous chapter. In the preceding example, match (), replace (), serach (), and split () can also be used in common strings.

Var box = 'Mr. lee is Lee '; alert (box. match ('L'); // locate L and return L; otherwise, return nullalert (box. search ('L'); // locate the location of L, and indexOf type alert (box. replace ('L', 'Q'); // replace L with Qalert (box. split (''); // split into strings by spaces

Other methods

Alert (String. fromCharCode (76); // L, the output Ascii code value

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

1. if the string should be placed before the string parameter in the alphabet, a negative number is returned. (Majority-1)
2. if the string is equal to the string parameter, 0 is returned.
3. if the string should be placed after the string parameter in the self-attached table, a positive number is returned. (Majority 1)

[task]var box = 'Lee';alert(box.localeCompare('apple'));//1alert(box.localeCompare('Lee'));//0alert(box.localeCompare('zoo'));//-1

HTML method

The above is to generate an html tag through JS. based on experience, it is of little use.

Var box = 'Lil'; alert (box. link ('http: // www.jb51.net'); // hyperlink

The tutorial content is from the JavaScript tutorial by Li Yanhui.

The following is an article prepared by other netizens:

Overview of basic packaging types

In fact, every time you read a basic type value, the background will create a corresponding basic packaging type object, so that you can call some methods to operate on the data;

Var box = 'Mr. lee '; // defines a String; var box2 = box. substring (2); // cut the first two digits of the string; console. log (box2); // output New string; =>. lee; // variable box is a String type, while box. substring (2) also indicates that it is an object (only the object can call the method); console. log ('Mr. lee '. substring (3); // call the method directly using the string value => Lee;

The main difference between the reference type and the basic packaging type is the lifetime of the object;
Automatically created objects of the basic packaging type only exist in the execution instant of a line of code and are immediately destroyed;
This means that we cannot add attributes and methods for basic type values at runtime;

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; automatically executed in the background;
1. literal writing

Var box = 'Mr. lee '; // literal; box. name = 'Lil'; // invalid attribute; box. age = function () {// invalid method; return 100 ;}; console. log (box. substring (3); // => Lee; console. log (typeof box); // => string; console. log (box. name); // => undefined; console. lgo (box. age (); // => error;

2. writing new operators

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

// The preceding literal declaration and the new operator declaration demonstrate the differences between them;
// However, both the literal and new operators can use its built-in method (substring );

Binary Boolean type

// The Boolean type does not have a specific attribute or method;

Three-Number type

// The Number type has some static attributes (called directly by Number without the new operator) and methods;

1. static attributes of the Number object

MAX_VALUE indicates the maximum number;
MIN_VALUE indicates the minimum value;
NaN is not a numerical value;
NEGATIVE-infinity negative infinity, overflow returns this value;
POSITIVE_INFINITY infinity, overflow returns this value;
Prototype, used to add new attributes and methods;

2. method of Number object

ToString () converts a value to a string and can be converted to hexadecimal notation;
ToLocaleString () converts strings based on the local numeric format;
ToFixed () retains the number after the decimal point and converts it to a string;
ToExponential () indicates the number in an exponential form;
ToPrecision () refers to a number in the form of an index or a vertex;

Four String types

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

1. String object attributes

Length returns the character length of a string;
Constructor returns the function for creating a String object;
Prototype extends the String definition by adding properties and methods; 2. String object character method
CharAt (n) returns the character at the specified index position;
CharCodeAt (n) returns the encoding of characters at the specified index location in Unicode format;
Var box = 'Mr. Lee ';
Console. log (box. charAt (1); // => r;
Console. log (box. charCodeAt (1); // => 114;
Console. log (box [1]) // => r; truncate by array; 3. String object String operation method

Concat (str1. .. str2) concatenates string parameters to the string that calls this method;
Slice (n, m) returns the string between n and m;
Substring (n, m) is the same as above;
Substr (n, m) returns m strings starting with n;
Var box = 'Mr. Lee ';
Console. log (box. concat ('OK! '); // => Mr. Lee OK !;
Console. log (box. slice (3); // => Lee; (truncates all the characters after index 3 );
Console. log (box. substring (3, 5); // => Le; (truncate the characters from index 3 to index 5); 4. String object String position method

IndexOf (str, n) searches for the first str from index n and returns the index value;
LastIndexOf (str, n) searches for the first str from index n and returns the index value;
Var box = 'Mr. Lee is Lee ';
Console. log (box. indexOf ('L'); // => 3; (the index value of the first L searched from the front to the back is 3 );
Console. log (box. lastIndexOf ('L'); // => 10; (the index value of the first L searched from the back to the front is 10 );
Console. log (box. indexOf ('L', 5); // => 10; (the index value of the first L that is searched from 5th to 10 );
// If no string is found,-1 is returned;

// Find all L values;
Var box = 'Mr. Lee is Lee ';
Var boxarr = []; // array for storing L;
Var pos = box. indexOf ('L'); // Obtain the location of the first L;
While (pos>-1) {// if the position is greater than-1, L exists;
Boxarr. push (pos); // add the 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. This method creates a copy of the string, deletes all spaces in 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 // because trim () returns a copy of the string, the leading and trailing spaces in the original string remain unchanged; 5. string case-insensitive conversion method
ToLowerCase (str) converts all strings to lowercase;
ToUpperCase (str) converts all strings to uppercase;
ToLocaleLowerCase (str) converts all strings to lowercase and localized values;
ToLocaleLowerCase (str) converts all strings into uppercase and localized values. 6. String object String pattern matching method

// Detailed usage is described in regular expressions;
Match (pattern) returns the substring or null in pattern; // It is the same as pattern.exe c (str;
Replace (pattern, replacement) replaces pattern with replacement;
Search (pattern) returns the starting position of pattern in the string;
Split (pattern) returns the array split by the specified pattern string;
Var box = 'Mr. Lee is Lee ';
Var p =/L/g; // enable global regularization;
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. Other methods of the String object
FromCharCode (ascii) static method, outputs the corresponding Ascii code value;
LocaleCompare (str1, str2) compares two strings and returns the corresponding value; 8. String object HTML method
// Generate an html tag using JS, which is of little use;
Var box = "Lee ";
Console. log (box. link ('www .baidu.com '); // Lee;

Summary
// Because of the basic packaging type, the basic type value in JS can be accessed as an object;
// Basic type features:
// 1. Each packaging type is mapped to a basic type with the same name;
// 2. when accessing the basic type value in read mode, an object of the corresponding basic packaging type will be created to facilitate data operations;
// 3. Once the statement of the operation basic type value is executed, the newly created packaging object will be destroyed immediately;

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.