To facilitate the 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 behavior corresponding to their respective base types. In fact, whenever a basic type value is read, an object of the corresponding basic packaging type will be created in the background, so that some methods can be called to manipulate the data.
1. Overview of basic packaging types
var box = 'Mr. Lee';//定义一个字符串 var box2 = box.substring(2);//截掉字符串前两位 alert(box2);//输出新字符串
The variable box is a string type, and box.substring(2) indicates that it is an object (PS: only objects will call methods), and finally the processing result is assigned to box2. 'Mr. Lee' is a string type value. Logically speaking, it should not be an object and should not have its own methods, such as:
alert('Mr. Lee'.substring(2));//Call the method directly through the value
1. Literal writing:
var box = 'Mr. Lee';//字面量 box.name = 'Lee';//无效属性 box.age = function () {//无效方法 return 100; }; alert(box);//Mr. Lee alert(box.substring(2));//. Lee alert(typeof box);//string alert(box.name);//undefined alert(box.age());//错误
2.new operator writing method:
var box = new String('Mr. Lee');//new 运算符 box.name = 'Lee';//有效属性 box.age = function () {//有效方法 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 declaration and new operator declaration nicely illustrate the difference between them. But one thing is certain, that is, its built-in methods can be used regardless of literal form or new operator form. And the Boolean and Number properties are the same as String, and the three types can become basic packaging types.
PS: When using the new operator to create the above three types of objects, you can add properties and methods to yourself, but we recommend not to use it in this way, because it will make it impossible to distinguish whether it is a basic type value or a reference type. value.
2. Boolean type
The Boolean type has no specific properties or methods.
3. Number type
The Number type has some static properties (properties called directly through Number without the new operator) and methods.
Number static property
Methods of Number object
var box = 1000.789; alert(box.toString());//转换为字符串,传参可以转换进制 alert(box.toLocaleString());//本地形式,1,000.789 alert(box.toFixed(2));//小数点保留,1000.78 alert(box.toExponential());//指数形式,传参会保留小数点 alert(box.toPrecision(3));//指数或点形式,传参保留小数点
4. 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 of objects, such as valueOf(), toLocaleString() and toString() methods, but these methods all return the basic value of the string.
Character methods
var box = 'Mr.Lee'; alert(box.charAt(1));//r alert(box.charCodeAt(1));//114 alert(box[1]);//r,通过数组方式截取
PS: box[1] will display undefined in IE browser, so use it with caution.
String operation 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 位开始 alert(box.substring(-3));//Mr.Lee 负数返回全部 alert(box.substr(-3));//Lee,6+(-3)=3 位开始 var box = 'Mr.Lee'; alert(box.slice(3, -1));//Le 6+(-1)=5, (3,5) alert(box.substring(3, -1));//Mr. 第二参为负,直接转 0,并且方法会把较小的数字提前,(0,3) alert(box.substr(3, -1));//'' 第二参数为负,直接转 0 ,(3,0)
PS: IE's JavaScript implementation has a problem when handling negative values passed to the substr() method. It will return the original string, so remember when using it.
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,从指定的位置向前搜索
PS: If the desired string is not found, -1 is returned.
Example: Find all L’s.
var box = 'Mr.Lee is Lee';//包含两个 L 的字符串 var boxarr = [];//存放 L 位置的数组 var pos = box.indexOf('L');//先获取第一个 L 的位置 while (pos > -1) {//如果位置大于-1,说明还存在 L boxarr.push(pos);//添加到数组 pos = box.indexOf('L', pos + 1);//从新赋值 pos 目前的位置 } alert(boxarr);//输出
Case conversion method
var box = 'Mr.Lee is Lee'; alert(box.toLowerCase());//全部小写 alert(box.toUpperCase());//全部大写 alert(box.toLocaleLowerCase()); alert(box.toLocaleUpperCase());
PS: Only a few languages (such as Turkish) have local-specific upper and lower case localization. Generally speaking, the localization effect is consistent whether it is localized or not.
String pattern matching method
The application of regular expressions in strings has been discussed in detail in the previous chapters and will not be repeated here. The above match(), replace(), serach(), and split() can also be used in ordinary strings.
var box = 'Mr.Lee is Lee'; alert(box.match('L'));//找到 L,返回 L 否则返回 null alert(box.search('L'));//找到 L 的位置,和 indexOf 类型 alert(box.replace('L', 'Q'));//把 L 替换成 Q alert(box.split(' '));//以空格分割成字符串
其他方法
alert(String.fromCharCode(76));//L,输出 Ascii 码对应值
localeCompare(str1,str2)方法详解:比较两个字符串并返回以下值中的一个;
1.如果字符串在字母表中应该排在字符串参数之前,则返回一个负数。(多数-1)
2.如果字符串等于字符串参数,则返回 0。
3.如果字符串在自附表中应该排在字符串参数之后,则返回一个正数。(多数 1)
[task]var box = 'Lee'; alert(box.localeCompare('apple'));//1 alert(box.localeCompare('Lee'));//0 alert(box.localeCompare('zoo'));//-1
HTML 方法
以上是通过 JS 生成一个 html 标签,根据经验,没什么太大用处,做个了解。
var box = 'Lee'; alert(box.link('http://www.jb51.net'));//超链接
教程内容来自 李炎恢老师JavaScript教程
下面是其它网友整理的文章:
一 基本包装类型概述
实际上,每当读取一个基本类型值的时候,后台就会创建一个对应的基本包装类型的对象,从而能够调用一些方法来操作这些数据;
var box = 'Mr.Lee'; // 定义一个String字符串; var box2 = box.substring(2); // 截掉字符串前两位; console.log(box2); // 输出新字符串;=>.Lee; // 变量box是一个字符串String类型,而box.substring(2)又说明它是一个对象(只有对象才会调用方法); console.log('Mr.Lee'.substring(3)); // 直接通过字符串值来调用方法=>Lee;
引用类型和基本包装类型的主要区别就是对象的生存期;
自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即被销毁;
这意味着我们不能在运行时为基本类型值添加属性和方法;
var s1 = 'some text'; // => var s1 = new String('some text');
var s2 = s1.substring(5); // => var s2 = s1.substring(5);
// s1 = null; 销毁这个实例;后台自动执行;
1.字面量写法
var box = 'Mr.Lee'; // 字面量; box.name = 'Lee'; // 无效属性; box.age = function(){ // 无效方法; return 100; }; console.log(box.substring(3)); // =>Lee; console.log(typeof box); // =>string; console.log(box.name); // =>undefined; console.lgo(box.age()); // =>错误;
2.new运算符写法
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 above literal declaration and new operator declaration well demonstrate the difference between them;
// However, whether it is a literal or the new operator, you can use its built-in method (substring);
Two Boolean types
//The Boolean type has no specific properties or methods;
Three Number types
//The Number type has some static properties (directly called through Number without the new operator) and methods;
1. Static properties of Number object
MAX_VALUE represents the maximum number;
MIN_VALUE represents the minimum value;
NaN Not a numerical value;
NEGATIVE-INFINITY Negative infinity, overflow returns this value;
POSITIVE_INFINITY Infinity, overflow returns this value;
prototype Prototype, used to add new properties and methods;
2. Methods of Number object
toString() Convert the value into a string, and can convert the base;
toLocaleString() Convert string according to local number format;
toFixed() Convert the number to a string by retaining the specified number of digits after the decimal point;
toExponential() represents the number in exponential form;
toPrecision() represents numbers in exponential form or point form;
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 length of the string;
constructor Returns the function that creates a String object;
prototype Expand the string definition by adding attributes and methods; 2. String object character method
charAt(n) Returns the character at the specified index position;
charCodeAt(n) Returns the encoding of the character at 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;Interception through array; 3.String object string operation method
concat(str1...str2) Concatenates the string parameters to the string calling the method;
slice(n,m) Returns the string between string position n and m;
substring(n,m) Same as above;
substr(n,m) Returns m strings starting at string position n;
var box = 'Mr.Lee';
console.log(box.concat('Ok!')); // =>Mr.Lee OK!;
console.log(box.slice(3)); // =>Lee;(Intercept all subsequent characters starting from index 3);
console.log(box.substring(3,5)); // =>Le;(Intercept characters from index 3 to index 5); 4.String object string position method
indexOf(str,n) Search the first str backward starting from index n and return the searched index value;
lastIndexOf(str,n) Searches forward for the first str starting from index n, and returns the searched index value;
var box = 'Mr.Lee is Lee';
console.log(box.indexOf('L')); // =>3;(The index value of the first L searched from front to back is 3);
console.log(box.lastIndexOf('L')); // =>10;(The index value of the first L searched from back to front is 10);
console.log(box.indexOf('L',5)); // =>10;(The index value of the first L searched backward from the 5th one is 10);
//If the string to be searched is not found, return -1;
// Find all L;
var box = 'Mr.Lee is Lee';
var boxarr = []; var boxarr
var pos = box.indexOf('L'); var pos = box.indexOf('L'); // Get the position of the first L;
boxarr.push(pos);
}
console.log(boxarr); // [3,10]
// trim() method
// ECMAScript5 defines the trim() method for all strings; this method will create a copy of the string, remove all leading and suffix spaces, and then return 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 original string The leading and suffix spaces will remain unchanged; 5. String object string case conversion method
toLowerCase(str) Convert all strings to lowercase;
toUpperCase(str) Convert all strings to uppercase;
toLocaleLowerCase(str) Converts all strings to lowercase and localizes them;
toLocaleLowerCase(str) Converts all strings to uppercase and localizes them; 6. Pattern matching method of String object string
// The specific usage method is introduced in the regular rules;
match(pattern) Returns the substring in pattern or null; // Same as pattern.exec(str);
replace(pattern,replacement)replace pattern with replacement;
search(pattern) Returns the starting position of pattern in the string;
split(pattern) Returns an array in which the string is split according to the specified pattern;
var box = 'Mr.Lee is Lee';
var p = /L/g;
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 String object
fromCharCode(ascii) Static method, outputs the corresponding value of the Ascii code;
localeCompare(str1,str2) Compares two strings and returns the corresponding value; 8. String object HTML method
// Generate an html tag through JS, which is of little use;
var box = "Lee";
console.log(box.link('www.baidu.com')); //Lee;
5 Summary
// Because of the basic packaging type, basic type values in JS can be accessed as objects;
//Basic type characteristics:
// 1. Each packaging type is mapped to a basic type with the same name;
// 2. When accessing a basic type value in read mode, an object of the corresponding basic packaging type will be created, thus facilitating data operations;
// 3. Once the statement that operates the basic type value is executed, the newly created packaging object will be destroyed immediately;