JavaScript - Basic Wrapper Type

JavaScript - Basic Wrapper Type

1. Basic Concepts

       To facilitate manipulation of primitive values , ECMAScript provides three 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, whenever a basic type value is read, an object of the corresponding basic wrapper type is created in the background, so that some methods can be called to manipulate the data.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>基本包装类型举例</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        alert(a);                //pangtong
        alert(typeof a);         //string
        alert(a.substring(4));   //tong    索引0开始,从第2个位置开始截取到末尾的字符串输出
        alert(a.indexOf('g'));   //3
    </script>
</body>
</html>

分析:
对象.方法(参数),这种写法是引用类型的写法。
基本包装类型是基本类型,但又是特殊的引用类型,可以调用系统内置的方法。

Two, two ways of writing

[1] Literal writing

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>基本包装类型字面量写法</title>
</head>
<body>
    <script type="text/javascript">
        //字面量写法
        var student = 'pangtong';
        student.name = 'tong';
        student.age = function (){
            return 18;
        };
        alert(student);                 //pangtong
        alert(typeof student);          //string
        alert(student.substring(4));    //tong
        alert(student.name);            //undefined
        alert(student.age());           //报错
    </script>
</body>
</html>

[2] How to write the new operator

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>基本包装类型new运算符写法</title>
</head>
<body>
    <script type="text/javascript">
        //new运算符写法
        var student = new String('pangtong');
        student.name = 'tong';
        student.age = function (){
            return 18;
        };
        alert(student);                 //pangtong
        alert(typeof student);          //object
        alert(student.substring(4));    //tong
        alert(student.name);            //tong
        alert(student.age());           //18
    </script>
</body>
</html>

[3] Differences and connections between the two writing methods

       Basic types cannot create custom properties and methods for themselves, but can call system built-in properties and methods. However, the new operator form can create custom properties and methods, and can also call system built-in properties and methods.
       Regardless of the literal form or the new operator form, the built-in methods of the system can be called. And the Boolean and Number properties are the same as String, and the three types can become basic wrapper types.
       When using the new operator to create objects of three types, Boolean, Number, and String, you can add properties and methods to yourself, but it is not recommended to use them in this way, which will make it impossible to distinguish whether it is a basic type value or a reference type value.

3. Boolean type

The Boolean type has no specific properties or methods.

4. Number type

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

1) Number static property

[1] MAX_VALUE represents the maximum number
[2] MIN_VALUE represents the minimum value
[3] NaN is not a numeric value
[4] NEGATIVE_INFINITY negative infinity, overflow returns this value
[5] POSITIVE_INFINITY is infinite, overflow returns this value
[6] prototype prototype, used to add new properties and methods
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Number静态属性</title>
</head>
<body>
    <script type="text/javascript">
        //Number静态属性
        var a = 500;
        alert(a.MAX_VALUE);       //这种写法叫做属性
        alert(Number.MAX_VALUE);  //这种写法(类型.属性)叫做静态属性
    </script>
</body>
</html>

2) Number static method

[1] toString() converts the value into a string, and can convert the base
[2] toLocaleString() converts to a string according to the local number format
[3] toFixed() retains the specified number of digits after the decimal point and converts it to a string
[4] toExponential() represents the number in exponential form, retains the specified number of digits after the decimal point and converts it into a string
[5] toPrecision() expresses the number in exponential form or point form, retains the specified number of digits after the decimal point and converts it into a string
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>Number静态方法</title>
</head>
<body>
    <script type="text/javascript">
        //Number静态方法

        //toString()
        var a = 1500;
        var b = 1500.678679;
        alert(a);                          //1500
        alert(typeof a);                   //number
        alert(a.toString());               //1500
        alert(typeof a.toString());        //string

        //toLocaleString()
        alert(a.toLocaleString());         //1,500
        alert(typeof a.toLocaleString());  //string

        //toFixed();
        alert(b);                            //1500.678679
        alert(typeof b);                     //number
        alert(b.toFixed(3));                 //1500.679
        alert(typeof b.toFixed(3));          //string
    </script>
</body>
</html>

5. String type

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

1) String object properties

[1] length returns the character length of the string
[2] The constructor returns the function that creates the String object
[3] prototype extends the string definition by adding properties and methods
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型三个属性</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        alert(a.length);        //8
        alert(a.constructor);   //function String(){}
    </script>
</body>
</html>

2) String object method

String also contains generic methods for objects, such as the valueOf(), toLocaleString(), and toString() methods, but these methods all return the basic value of the string.

【1】Character method

[1] charAt(n) returns the character at the specified index position
[2] charCodeAt(n) returns the character at the specified index position in Unicode encoding
[Supplement] It can also be obtained by array method, a[1] will display undefined in IE browser, so be careful when using it.
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        alert(a.charAt(2));         //n,索引从0开始
        alert(a.charCodeAt(1));     //97,索引从0开始
        alert(a[1]);                //a
    </script>
</body>
</html>

【two】character method

[1] concat(str1...str2) concatenates the string parameters to the string that calls the method
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        //concat()方法
        alert(a.concat('  is ',' a ',' girl ','!'));   //pangtong is a girl!
    </script>
</body>
</html>
[2] slice(n,m) returns the string at the position between the string n and m

*Including n excluding m.
*Index starts at 0.
* If there is only one parameter, return all characters starting from this parameter and backward.
* If there is only one negative parameter, first get the length of the string, then add the negative value to the length of the string, and the obtained number is the position where the interception starts. For example,
var a = 'pangtong';alert(a.slice(-2)); , the result of printing is ng, the length of the string is 8, 8+(-2)=6, from the position of 6 Start capturing to the end.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        //slice(n,m)方法
        alert(a.slice(0,3));   //pan
        alert(a.slice(4));     //tong
        alert(a.slice(-2));    //ng
        alert(a.slice(4,-2));  //to
        alert(a.slice(-2,-1)); //n
    </script>
</body>
</html>
[3] substring(n,m) is the same as above

*The usage of positive parameters is the same as slice
* If there is only one negative parameter, the whole string will be returned
* If one of the two parameters is positive and the other negative, the parameter is negative and directly transferred to 0, and the method will advance the smaller number, such as Say,
var a = 'pangtong';alert(a.substring(3,-3)); The print result is pan, and the second parameter is a negative number, so it directly becomes (3, 0), and the small advance (0 , 3)

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        //substring(n,m)方法
        alert(a.substring(0,3));   //pan
        alert(a.substring(4));     //tong
        alert(a.substring(-3));    //pangtong
        alert(a.substring(3,-3));  //pan
        alert(a.substring(-6,-3)); //空
    </script>
</body>
</html>
[4] substr(n,m) returns m strings starting with string n

*IE's JavaScript implementation has a problem with handling negative values ​​passed to the substr() method, which returns the original string, and below IE8 returns the original full string.
*If the second parameter is a negative value, it will directly change to 0, and return null
*If the first parameter is a negative value, the index of -2 is the position of the original index of 2.
If there is only one parameter, intercept from the position until the end of the string

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        alert(a.substr(4));    //tong
        alert(a.substr(2,4));  //ngto
        alert(a.substr(-3));   //ong   在IE8以下会返回原始全部字符串pangtong
        alert(a.substr(2,-2)); //空    如果第二个参数是负值,则直接变为0,返回空
        alert(a.substr(-2,2)); //ng    如果第一个参数是负值,则索引为-2的就是原来索引为2的位置
    </script>
</body>
</html>

[3] String location method

【1】indexOf(str, n)

Search backward from the specified position to the position where the first character appears, from left to right, and return the index value of the search

【2】lastIndexOf(str, n)

Search forward from the specified position to the position where the first character appears, from right to left, and return the index value of the search

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var a = 'pangtong';
        alert(a.indexOf());              //-1 如果没有找到想要的字符串,则返回-1。
        alert(a.indexOf('g'));           //3  从最初的位置开始向后搜索第一个字符出现的位置,由左向右的顺序
        alert(a.indexOf('n',2));         //2  从指定的位置开始向后搜索第一个字符出现的位置,由左向右的顺序
        alert(a.lastIndexOf('g'));       //7  从最后开始向前搜索第一个字符出现的位置,由右向左的顺序
        alert(a.lastIndexOf('n',7));     //6  从指定的位置开始向前搜索第一个字符出现的位置,由右向左的顺序
    </script>
</body>
</html>
【3】Exercise questions
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        //练习题
        //题目:如果在下面字符串中找到所有'n'出现的位置
        var s = 'pangtong';
        //第一步:写一个存放'n'的空数组
        var as = [];
        //第二步:获取第一个'a'的位置
        var pos = s.indexOf('n');
        //第三步:循环,如果pos大于-1,说明还存在a
        while(pos > -1){
            //第四步:将找到的a的位置添加进数组
            as.push(pos);
            //第五步:将位置指针指向下一个相邻位置,继续寻找
            pos = s.indexOf('n',pos+1);
        }
        //最后一步:输出
        alert(as);   //2,6
    </script>
</body>
</html>

[four] case conversion method

[1] toLowerCase(str) converts all strings to lowercase
[2] toUpperCase(str) converts all strings to uppercase
[3] toLocaleLowerCase(str) converts all strings to lowercase and localizes them
[4] toLocaleupperCase(str) converts all strings to uppercase and localizes them

Only a few languages ​​(such as Turkish) have place-specific case locality, and in general, the effect of localization is the same.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        //大小写转换
        var str = 'Pangtong';
        alert(str.toLowerCase());
        alert(str.toUpperCase());
        alert(str.toLocaleLowerCase());
        alert(str.toLocaleUpperCase());
        //只有几种语言(如土耳其语)具有地方特有的大小写本地性,一般来说,是否本地化效果都是一致的。
    </script>
</body>
</html>

[5] Pattern matching method for strings

[1] match(pattern) returns the substring in pattern, and returns null if not found
【2】replace(pattern, replacement) 用replacement 替换pattern
[3] search(pattern) returns the starting position of pattern in the string (returns the value of indexOf of the found string)
[4] split(pattern) Returns an array of strings split by the specified pattern

match(), replace(), serach(), split() can also be used in normal strings.

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var s = 'pangtong';
        alert(s.match('t'));        //t
        alert(s.match('b'));        //null
        alert(s.replace('t','T'));  //pangTong
        alert(s.search('t'));       //4
        alert(s.split('t'));        //pang,ong
    </script>
</body>
</html>

[6] Other methods (not commonly used, just understand)

[1] fromCharCode(ascii) static method, output the corresponding value of Ascii code
[2] localeCompare(str1, str2) compares two strings and returns the corresponding value
  • localeCompare(str1, str2): Compares two strings and returns one of the following values:
  • * Returns a negative number if the string should come before the string argument in the alphabet. (majority-1)
  • * Returns 0 if the string is equal to the string argument.
  • Returns a positive number if the string should come after the string argument in the alphabet. (most 1)
【3】link(URL)
<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title>String类型方法</title>
</head>
<body>
    <script type="text/javascript">
        var s = 'pangtong';
        alert(s.link('www.baidu.com'));   //<a href="www.baidu.com">pangtong</a>
    </script>
</body>
</html>

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325496765&siteId=291194637