search
HomeWeb Front-endJS TutorialIntroduction to basic packaging types of javascript_javascript skills

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;

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),