5.6 基本包装类型(JavaScript高级程序设计 第3版)

为了便于操作基本类型值,ECMAScript提供了3个特殊的引用类型:Boolean、Number和String。

这些每当读取一个基本类型的时候,后台就会创建一个对应的基本包装类型的对象,从而让我们调用一些方法来操作这些数据。

引用类型与基本包装类型的主要区别就是对象的生存期。使用new操作符创建的引用类型的实例,在执行流离开当前作用域之前一直保存在内存中。而自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即被销毁。如下:

var s1 = "some text";
s1.color = "red";
alert(s1.color);   //undefined

所有基本包装类型的对象在转换为布尔类型时值都属true。

 

5.6.1  Boolean类型

Boolean类型是与布尔值对应的引用类型。创建Boolean对象,如下:

var booleanObject = new Boolean(true);

Boolean类型的实例重写了valueOf()方法,返回基本类型值true或false;重写了toString()方法,返回字符串true或false。最常见的问题就是在布尔值表达式中使用对象:

var falseObject = new Boolean(true);
var result = falseObject && true;
alert(result);        //true 布尔表达式中的所有对象都会被转换成true

var falseValue = false;
result = falseValue && true;
alert(result);        //false

基本类型与引用类型的布尔值有两个区别:

typeof操作符对基本类型返回"boolean";对引用类型返回"object";

instanceof操作符对基本类型返回false,对引用类型返回true。

var falseObject = new Boolean(true);
var falseValue = false;

alert(typeof falseObject);                 //object
alert(typeof falseValue);                  //boolean
alert(falseObject instanceof Boolean);     //true
alert(falseValue instanceof Boolean);      //false

//from page 120

建议永远不要用Boolean对象。

 

5.6.2  Number类型

Number是与数字值对应的引用类型。创建Number对象,如下:

var numberObject = new Number(10);

Number类型重写了valueOf()方法返回对象表示的基本类型的数值;重写了toLocaleString()和toString()方法都返回字符串形式的数值。

 

Number类型提供的其他方法:toFixed()、toExponential()、toPrecision()

A:toFixed():传入一个参数,表示返回的小数位的位数,方法会按照制定的小数位返回数值的字符串表示,如果小数位比指定的多,则会舍入,如下:

var num = 10;
alert(num.toFixed(2));   //10.00
var num1 = 10.005;
alert(num1.toFixed(2));  //10.01

//from page 121

 

B:toFixed():返回以指数表示法(e表示法)表示的数值的字符串形式。也接收一个参数,也指定输出结果中的小数位数,如下:

var num = 10;
alert(num.toExponential(1));   //1.0e+1

C:toPrecision():表示某个数值的最合适的格式。接收一个参数,表示数值的所有数字的位数,如下:

var num = 99;
alert(num.toPrecision(1));  //1e+2
alert(num.toPrecision(2));  //99
alert(num.toPrecision(3));  //99.0

和Boolean类型一样,在使用typeof和instanceof操作符测试基本类型与引用类型的数值时,得到的结果完全不同,如下:

var numberObject = new Number(10);
var numberValue = 10;
alert(typeof numberObject);            //object
alert(typeof numberValue);             //number
alert(numberObject instanceof Number); //true
alert(numberValue instanceof Number);  //false

建议永远不要用Number对象。

 

5.6.3  String类型

String类型是字符串的对象包装类型,创建方式:

var stringObject = new String("hello world");

继承的valueOf()、toLocaleString()和toString()方法,都返回对象所表示的基本字符串值。

String类型的每个实例都有length属性:

var stringObject = new String("hello world");
alert(stringObject.length);    //11

1.字符方法

① charAt():接受一个参数,即基于0的字符位置,以单字符串的形式返回给定位置的那个字符。

② charCodeAt():接受一个参数,即基于0的字符位置,返回给定位置字符的字符编码;

③ stringValue():可以用方括号加数字索引来访问字符串中的特定字符。

var stringValue = "hello world";

alert(stringValue.charAt(1));        //e
alert(stringValue.charCodeAt(1));    //101
alert(stringValue[1]);               //e

2.字符串操作方法

① concat():用于将一个或多个字符串拼接起来,返回新字符串;

var stringValue = "hello ";
var result = stringValue.concat("world");
var result1 = stringValue.concat("world","!");

alert(result);       //hello world
alert(result1);      //hello world!
alert(stringValue);  //hello 

下面三种方法都返回被操作字符串的一个子字符串。都接收一个或两个参数,如果没有第二个参数,则将字符串的末尾作为结束位置。

② slice():(起始位置,结束位置),不包含结束位置

③ substr():(起始位置,返回字符串的个数)

④ substring():(起始位置,结束位置),不包含结束位置

var stringValue = "hello world";

alert(stringValue.slice(3));         //lo world
alert(stringValue.substring(3));     //lo world
alert(stringValue.substr(3));        //lo world

alert(stringValue.slice(3,7));       //lo w
alert(stringValue.substring(3,7));   //lo w
alert(stringValue.substr(3,7));      //lo worl

//from page 124

当传递的参数是负数时:

slice()会将传入的负数和字符串长度相加;substr()将负的第一个参数加上字符串长度,第二个参数转换为0;substring()所有负数都转换成0。

var stringValue = "hello world";

alert(stringValue.slice(-3));         //rld
alert(stringValue.substring(-3));     //hello world
alert(stringValue.substr(-3));        //rld

alert(stringValue.slice(3,-4));       //lo w
alert(stringValue.substring(3,-4));   //hel
alert(stringValue.substr(3,-4));      //空

3.字符串位置方法

两个方法:indexOf()和lastIndexOf();两个方法都是从一个字符串中搜索给定的子字符串,返回字符串的位置,没有找到返回-1。

两个方法区别在于:indexOf()从字符串开头查找;lastIndexOf()从末尾开始查找。

var stringValue = "hello world";

alert(stringValue.indexOf("o"));         //4  "hello"中的o
alert(stringValue.lastIndexOf("o"));     //7  "world"中的o

//from page 125

可以传入第二个参数:(查找的字符,开始位置)

var stringValue = "hello world";

alert(stringValue.indexOf("o", 6));         //7  "world"中的o
alert(stringValue.lastIndexOf("o", 6));     //4  "hello"中的o

//from page 125

下面例子,查找一段话中的做有某个字符:

var stringValue = "Want to see Aska Yang's concert";
var positions = new Array();
var pos = stringValue.indexOf("n");

while( pos > -1 ){
	positions.push(pos);
	pos = stringValue.indexOf("n", pos+1);
}

alert(positions);   //2,19,26

//from page 125

4.trim()方法

这个方法会创建一个字符串的副本,删除前置及后缀的左右空格,然后返回结果:

var stringValue = "   hello world   ";
var trimmedStringValue = stringValue.trim();
alert(stringValue);            //"   hello world   "
alert(trimmedStringValue);     //"hello world"

//from page 126

5.字符串大小写转换方法

四个方法:

① toLowerCase():转小写

② toUpperCase():转大写

③ toLocaleLowerCase():转小写,针对特定区域实现

④ toLocaleUpperCase():转大写,针对特定区域实现

var stringValue = "Hello World";

alert(stringValue.toLowerCase());          //hello world
alert(stringValue.toUpperCase());          //HELLO WORLD
alert(stringValue.toLocaleLowerCase());    //hello world
alert(stringValue.toLocaleUpperCase());    //HELLO WORLD

//from page 126

6.字符串的模式匹配方法

① match() 方法:接收一个参数,要么是正则表达式,要么是RegExp()。本质与RegExp的exec()方法相同。

var text = "cat,bat,sat,fat";
var pattern = /.at/;
//与pattern.exec(text)相同
var matches = text.match(pattern);
alert(matches.index);       //0
alert(matches[0]);          //cat
alert(pattern.lastIndex);   //0

② search()方法:接收一个参数,由字符串或RegExp对象指定的一个正则表达式,返回字符串中第一个匹配项的索引。

var text = "cat,bat,sat,fat";
var pos = text.search(/at/);
alert(pos);       //1   即"at"在字符串中第一次出现的位置

③ replace()方法:两个参数,(RegExp对象或者字符串,字符串或函数)。

如果第一个参数是字符串,则只会替换第一个子字符串;想替换全部必须提供一个正则表达式,且必须指定全局(g)标志。

var text = "cat,bat,sat,fat";
var result = text.replace("at", "ond");
alert(result);        // cond,bat,sat,fat
result = text.replace(/at/g, "ond");
alert(result);        // cond,bond,sond,fond   

如果第二个参数是字符串,那么还可以使用一些特殊的字符序列,将正则表达式操作得到的值插入到结果字符串中。

字符序列替换文本
$$$
$&匹配整个模式的子字符串。与RegExp.lastMatch的值相同。
$'匹配的子字符串之前的子字符串。与RegExp.leftMatch的值相同。
$`匹配的子字符串之后的子字符串。与RegExp.rightMatch的值相同。
$n匹配第n个捕获组的子字符串,其中n等于0~9。
$nn匹配第nn个捕获组的子字符串,其中n等于01~99。
var text = "cat, bat, sat, fat";
var result = text.replace(/(.at)/g, "word ($1)");
alert(result);        // word (cat), word (bat), word (sat), word (fat)

如果第二个参数是一个函数:

只有一个匹配项:传递三个参数(模式的匹配项,模式匹配项在字符串中的位置,原始字符串);

正则表达式定了多个捕获组的情况下:(模式的匹配项,第一个捕获组的匹配项,第二个捕获组的匹配项...,模式匹配项在字符串中的位置,原始字符串)

function htmlEscape(text){
	return text.replace(/[<>"&]/g, function (match, pos, originalText){
		switch(match){
			case "<":
				return "&lt;";
			case ">":
				return "&gt;";
			case "&":
				return "&amp;";
			case "\"":
				return "&quot";
		}
	});
}

alert(htmlEscape("<p class=\"greeting\">Aska Yang!</p>"));
//&lt;p class=&quotgreeting&quot&gt;Aska Yang!&lt;/p&gt;

//from page 128

 ④ split() :基于指定的分隔符将一个字符分割成多个子字符串,并将结果放在一个数组中。分隔符可以使字符串,也可以是RegExp对象,可以传第二个参数,用于指定数组的大小。

var colorText = "red,blue,green,yellow";
var color1 = colorText.split(",");
var color2 = colorText.split(",",2);
var color3 = colorText.split(/[^\,]+/);
alert(color1);    //["red","blue","green","yellow"]
alert(color2);    //["red","blue"]
alert(color3);	  //["", ",", ",", ",", ""]

//from page 128

split() 方法中正则表达式的支持因浏览器而异,要多在各种浏览器下多做些测试。

7.localeCompare()方法

比较两个字符串,并返回下列值中的一个:

① 如果字符串在字母表中应该排在字符串参数之前,则返回负数(多数情况时-1)

② 如果字符串在字母表中应该排在字符串参数之后,则返回正数(多数情况时1)

③ 如果字符串等于字符串参数

var stringValue = "yellow";
alert(stringValue.localeCompare("brick"));
alert(stringValue.localeCompare("yellow"));
alert(stringValue.localeCompare("zoo"));

//from page 129

由于部分情况可能返回的不是-1,是其他负数,所以实现时最好使用result>0或result>0来执行不同的代码。

8.fromCharCode()方法

接收一个或多个字符编码,返回对应的字符串。本质上是与charCodeAt()执行相反的操作。

alert(String.fromCharCode(104,101,108,108,111));   //hello

9.HTML方法

早期为了实现使用JavaScript动态格式化HTML的需求:

方法输出结果
anchor()<a name="name">string</a>
big()<big>string</big>
bold()<b>string</b>
 ....很多

不建议使用这些方法,因为他们创建的标记通常无法表达语义。

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值