SoFunction
Updated on 2025-02-28

An example analysis of basic packaging type of JavaScript reference type [Boolean, Number and String]

This article describes the basic wrapping type of JavaScript reference type. Share it for your reference, as follows:

In order to manipulate basic type values, ECDMAScript provides 3 special reference types - basic wrapper typesBooleanNumberandString. Whenever a primitive type value is read, the background will create an object of the corresponding primitive wrapper type.

var str = "Hello world";
var substr = ();

Equivalent to

var str = new String("Hello world");//Create an instance of String typevar substr = ();//Calling the substring() method on the instancestr = null;//Destroy instance

The basic packaging type is a special reference type. The difference between the reference type and the basic packaging type is as follows:

(1) The life of the object

An instance of a reference type created using the new operator exists in memory until the execution flow leaves the current scope, while an automatically created object of the basic wrapper type only exists at the moment of code execution and is then destroyed immediately, that is, properties and methods cannot be added to the basic wrapper type at runtime.

var str1 = "Hello world";
var str2 = new String("Hello World");
 = 20;
 = 20;
alert();//undefined
alert();//20

(2) Instanceof operator test results

useinstanceofOperator testing the base wrapper type instance will return true, and test the base type value will return false.

var str1 = "Hello World";
var str2 = new String("Hello world");
alert(str1 instanceof String);//false
alert(str2 instanceof String);//true

Boolean, Number, and String can be explicitly called to create objects of basic wrapper type, but do not do this as possible, because it is not easy to distinguish whether you are dealing with basic types or reference types.

The Object constructor returns an instance of the corresponding base wrapper type based on the type of the value passed in.

var str = new String("Hello world");
alert(str instanceof String);//true
var num = new Number(16);
alert(num instanceof Number);//true
var bool = new Boolean(true);
alert(bool instanceof Boolean);//true

Instance calls to basic wrapper typestypeOf()The method will return "Object", and the instance variable saves the basic type value.

var str = new String("Hello world");
alert(typeof str);//object
var num = new Number(16);
alert(typeof num);//object
var boolean = new Boolean(true);
alert(typeof boolean);//object

usenewThe operator calls the constructor of the basic wrapper type, which is different from directly calling the transformation function with the same name. The variables store instances of the basic wrapper type.

var str = String("Hello world");
alert(typeof str);//string
var num = Number(16);
alert(typeof num);//number
var bool = Boolean(true);
alert(typeof bool);//boolean

All objects of basic wrapper types are valued true when converted to a boolean type.

var boolean1 = new Boolean(false);
alert(boolean1);//false
alert(boolean1 && true);//true
var boolean2 = new Boolean(0);
alert(boolean2);//false
alert(boolean2 && true);//true
var boolean3 = new Boolean("");
alert(boolean3);//false
alert(boolean3 && true);//true

1. Boolean type

var boolean = new Boolean(true);

The instance of Boolean type has been rewrittenvalueOf()Method, return the corresponding basic type values ​​true and false; rewrittentoString()Method, return the strings "true" and "false".

2. Number type

var num = new Number(16);

The Number type has also rewritten inheritedvalueOf()toString()toLocaleString()Method, rewrittenvalueOf()The method returns the corresponding basic type value, and the other two methods return the corresponding string. You can pass a parameter representing the cardinality to the toString() method.

In addition to inherited methods, Number also provides methods to format numeric values ​​into strings:

(1)toFixed()Method: The passed parameter is a decimal place, and returns a string representation of the value.

(2)toExponential()Method: The passed parameter is a decimal place, returning the string form of a numeric value represented in exponential representation.

(3)toPrecision()Method: The passed parameter is the number of all array bits of the numeric value, does not contain the exponent part, and returns the string representation of the specified format.

3. String type

var str = new String("Hello world");

String type inheritedvalueOf()toString()toLocaleString()Method returns the string value represented by the object.

(1) Properties of String type instance.

lengthAttribute: Indicates the number of characters contained in a string.

(2) Methods of String type instances.

--- Character Method

The value of the string itself will not be modified, it will only return the substring and will have no effect on the original string.

1)charAt()Method: The passed parameter is a character position based on 0, returning the character at the given position.

2)charCodeAt()Method: The passed parameter is a character position based on 0, returning the character encoding of the given position.

---String operation method

1)concat()Method: The passed parameters are any multiple strings, returning the string obtained by splicing.

2)substr()slice()substring()Method: Three methods to create a new string based on a substring, pass one or two parameters, and return the substring. The first parameter specifies the start position of the substring, and the second parameter is optional.slice()andsubstring()The second parameter of , specifies the end position of the substring, and the second parameter of substr() specifies the length of the substring. When the passed parameter is a negative number,slice()The method adds negative values ​​to the string length.substr()The method adds the first negative value to the string length, and the second negative value to 0,substring()The method converts all negative values ​​to 0.

---String position method

Search for the given substring, return the position of the substring, and return -1 if it is not searched. The first parameter specifies the search substring, and the second parameter is optional, specifying the location where the search starts. ---

1)indexOf()Method: Search backward from scratch.

2)lastIndexOf()Method: Start from behind and search forward.

---trim()method

Create a copy of the string, delete the spaces of the prefix and suffix, and return the new string, and the original string remains unchanged.

---Stand case conversion method

1)toLowerCase()Method: General lowercase conversion method.

2)toUpperCase()Method: General capitalization conversion method.

3)toLocaleLowerCase()Method: Lowercase conversion method for specific regions.

4)toLocaleUpperCase()Method: Caps conversion method for specific regions.

---Stand pattern matching method

1)match()Method: Calling the match() method on a string is the same as calling the exec() method on a RegExp instance. Receives 1 parameter—regex or RegExp object. Returns an array whose first term is a string matching the entire pattern, and each item following is a string matching the individual subpatterns.

2)search()Method: Start from scratch and look backward. Receives 1 parameter—regex or RegExp object. Returns the index of the first match, and -1 is returned if no match result is found.

3)replace()Method: Replace the string. Receive 2 parameters - the first parameter is a regular expression or RegExp object or string (the string is not converted to a regular expression), and the second parameter is a string or function. If the first parameter is a string, it will only replace the first substring. If you want to replace the substring, you need to use a RegExp object with the g flag.

a. When the second parameter is a string, use a special character sequence to insert the value obtained by the regular expression operation into the result string.

Special character sequence Replace text
$$ $
$& Substrings matching the entire pattern
$' Substring before matching substring
$` Substring after matching substring
$n Match the substring of the nth sub-pattern, n equals 0-9. If no sub-pattern is defined in the regular expression, an empty string is used.
$nn Match the substring of the nn-th sub-pattern, nn equals 01-99. If no sub-pattern is defined in the regular expression, an empty string is used.
var str = "cat, fat, eat";
var result = (/(.at)/g, "my($1)");
alert(result);//my(cat), my(fat), my(eat)

b. When the second parameter is a function, more refined replacement operations can be implemented.

When there is only one match (i.e., a string matching a pattern), pass 3 parameters to the function - the pattern matching, the position of the pattern match in the string, and the original string. In the case where multiple subpatterns are defined in a regular expression, the parameters passed to the function are the match of the pattern, the match of the first subpattern, the match of the second subpattern,..., the position of the pattern match in the string, and the original string. Returns the replacement text.

var str = "<a href = \"\">link</a>";
var result = (/[<>"&]/g, function(match, positon, originalStr) {
  switch(match) {
    case "<":
      return "<";
    case ">":
      return ">";
    case "&":
      return "&";
    case "\"":
      return """;
  }
});
alert(result);//<a href = "">link</a>

4)split()Method: The first parameter is a delimiter (a string or a RegExp object, the string will not be converted to a regular expression), and the second parameter is optional, specifying the size of the returned string array. Returns the split string array.

var strs1 = ("|", 2);//["cat","fat","eat"]
var str = "cat|fat|eat";
var strs1 = ("|");
alert(strs1);//cat,fat,eat
var strs2 = ("|", 2);
alert(strs2);//cat,fat
var strs3 = (/[^\|]+/);
alert(strs3);//,|,|,

The delimiters of strs3 are "cat", "fat", "eat", so the first and last item of the array are returned.

---localeCompare() method:

Compare two strings. If the string should be arranged before the string parameters in the alphabet, return a negative number (mostly -1), if it is afterwards, return a positive number (mostly 1), and if it is equal, return 0.

alert("world".localeCompare("hello"));//1

---fromCharCode() method:

The static method of the String class, which receives one or more character encodings, converts them into a string, andcharCodeAt()It is the opposite operation.

alert((104, 101, 108, 108, 111));//"hello"

For more information about JavaScript, readers who are interested in reading this site's special topic:JavaScript object-oriented tutorial》、《Summary of common JavaScript functions techniques》、《Summary of JavaScript Errors and Debugging Skills》、《Summary of JavaScript data structure and algorithm techniques》、《Summary of JavaScript page element operation skills"and"Summary of JavaScript DOM skills

I hope this article will be helpful to everyone's JavaScript programming.