您的位置:首页 > Web前端 > JavaScript

说说 JavaScript 基本包装类型

2017-03-07 14:41 316 查看
为了便于操作基本类型的值,ECMAScript 提供了 3 个特殊的引用类型:Boolean、Number 和 String。

每当读取一个基本类型值的时候,后台会创建一个对应的基本包装类型的对象。

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

对基本包装类型的实例调用 typeof 都会返回 “object”,所以只有在绝对必要的情况下才显式调用。

Object 构造函数会根据传入值的类型返回相应的基本包装类型的实例:

var obj = new Object("some text");
console.log(obj instanceof String);//true


使用 new 调用基本包装类型的构造函数与直接调用同名的转型函数返回的类型的不一样的:

var value = "25";
var number = Number(value);//转型函数
console.log(typeof number);//number

var obj = new Number(value);//构造函数
console.log(typeof obj);//object


1 Boolean 类型

用处不大,特别是在布尔表达式中使用 Boolean 对象会造成误解,因为布尔表达式中的所有对象都会被转换为 true:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>Boolean 对象的误用(布尔表达式中所有的对象都会被转换为 true)</title>
</head>
<body>

<script type="text/javascript">
var falseObject = new Object(false);
var result = falseObject && true;
console.log(result);//true

var falseValue = false;
result = falseValue && true;
console.log(result);//false
</script>
</body>
</html>


因此,建议永远不要使用 Boolean 对象。

2 Number 对象

2.1 创建 Number 对象

var numberObject = new Number(10);


2.2 toString()

为 toString() 方法传递一个表示基数的参数,它会返回多少进制的数值的字符串形式:

var num = 10;
console.log(num.toString());//10
console.log(num.toString(2));//1010
console.log(num.toString(8));//12
console.log(num.toString(10));//10
console.log(num.toString(16));//a


2.3 toFixed()

toFixed() 方法会按照指定的小数位返回数值的字符串表示:

var num = 10;
console.log(num.toFixed(2));//10.00


如果数值本身包含的小数位比指定的还要多,那么接近指定的最大小数位的值就会舍入:

var num = 10.005;
console.log(num.toFixed(2));//10.01


toFixed() 方法很适合处理货币值,但依实现而异。

注意: 规范中规定 toFixed() 方法可以表示带有 0 ~ 20 个小数位的数值,但有的浏览器支持更多位数。

2.4 toExponential()

返回以指数表示法表示的数值的字符串形式,可以指定输出结果中的小数位数:

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


2.5 toPrecision()

可能会返回固定大小的格式,会可能返回指数格式,它会自动判断哪种格式合适。

它接收一个参数,即表示数值的所有数字的位数(不包括指数部分):

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


注意: 规范中规定 toPrecision() 方法可以表示带有 1 ~ 21 个小数位的数值,但有的浏览器支持更多位数。

2.6 建议

不建议直接直接实例化 Number 类型,因为在使用 typeof 和 instanceof 操作符测试基本类型数值与引用类型数值时,结果完全不同:

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


3 String 类型

使用 String 构造函数创建:

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


length 属性表示字符串中包含了多少字符。注意,即使字符串中吧包含双字节字符,也算是一个字符:

var stringValue = "hello world";
console.log(stringValue.length);//11


3.1 字符方法

charAt() 接受基于 0 的字符位置,返回给定位置的那个字符:

console.log(stringValue.charAt(1));//e


charCodeAt() 接受基于 0 的字符位置,返回给定位置的那个字符编码:

console.log(stringValue.charCodeAt(1));//101


ECMAScript 5 中可以使用方括号加数字索引的方式访问字符串中的特定字符:

console.log(stringValue[1]);//e


3.2 字符串方法

concat() 可将一个或多个字符串拼接起来,返回拼接后的新字符串:

var stringValue = "hello ";
var result = stringValue.concat("world");
console.log(result);//hello world
console.log(stringValue);//hello


concat() 可以接受任意多个参数,因此可以拼接任意多个字符串:

var stringValue = "hello ";
var result = stringValue.concat("world", "!");
console.log(result);//hello world!
console.log(stringValue);//hello


其他创建新字符串的方法

这些方法对原始字符串没有影响,如果没有给这些方法传递第二个参数,就会将字符串的长度作为结束位置。

方法名接受参数说明
slice()字符串开始位置、子字符串最后一个字符后面的位置(可选)如果参数是负数,会将负值与字符串的长度相加
substring()字符串开始位置、子字符串最后一个字符后面的位置(可选)将所有的负值转换为 0
substr()字符串开始位置、需要返回的字符个数(可选)负的第一个参数加上字符串长度,负的第二个参数转换为 0
//正值
var stringValue = "hello world";
console.log(stringValue.slice(3));//lo world
console.log(stringValue.substring(3));//lo world
console.log(stringValue.substr(3));//lo world
console.log(stringValue.slice(3, 7));//lo w
console.log(stringValue.substring(3, 7));//lo w
console.log(stringValue.substr(3, 7));//lo worl


//负值
console.log(stringValue.slice(-3));//rld
console.log(stringValue.substring(-3));//hello world
console.log(stringValue.substr(-3));//rld
console.log(stringValue.slice(3, -4));//lo w
console.log(stringValue.substring(3,-4));//hel
console.log(stringValue.substr(3,-4));//空字符串


3.3 字符串位置方法

indexOf() 和 lastIndexOf() 从一个字符串中搜索给定的子字符串,然后返回子字符串的位置(如果没有找到,则返回 -1)

她们的区别在于 indexOf() 是从前向后搜索;而 lastIndexOf() 是从后往前搜索:

可以通过循环调用 indexOf() 或 lastIndexOf() 来找到所有匹配的子字符串:

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>可以通过循环调用 indexOf 或 lastIndexOf 来查找所有匹配的字符串</title>
</head>
<body>

<script type="text/javascript">
var stringValue = "last night, I'm looking a good movie: La La Land";
var positions = new Array();
var pos = stringValue.indexOf("a");

while (pos > -1) {
positions.push(pos);
pos = stringValue.indexOf("a", pos + 1);
}
console.log(positions);//1,24,39,42,45
</script>
</body>
</html>


3.4 trim() 方法

ECMAScript 5 定义<
fe3c
/li>
她会创建一个字符串的副本,然后删除前缀以及后缀的所有空格,最后返回:

3.5 字符串大小写转换方法

toLowerCase() 和 toUpperCase() ,是不是很经典啊 O(∩_∩)O~

toLocaleLowerCase() 和 toLocalUpperCase() 是针对地区的特殊实现,如果不知道代码将在哪种语言环境中运行,最后还是用这两个方法。

<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>字符串大小写转换方法</title>
</head>
<body>

<script type="text/javascript">
var stringValue = "hello world";
console.log(stringValue.toLocaleUpperCase());//HELLO WORLD
console.log(stringValue.toUpperCase());//HELLO WORLD
console.log(stringValue.toLocaleLowerCase());//hello world
console.log(stringValue.toLowerCase());//hello world
</script>
</body>
</html>


3.6 字符串的模式匹配方法

match() 接收一个参数,可以是正则表达式或者是 RegExp 对象,她会返回一个数组,数组的第一项是与整个模式匹配的字符串,之后的每一项(如果有)是与正则表达式中的捕获组匹配的字符串:

var text = "cat,bat,sat,fat";
var pattern = /.at/;

//与 pattern.exec(text) 相同
var matches = text.match(pattern);
console.log(matches.index);//0
console.log(matches[0]);//cat
console.log(pattern.lastIndex);//0


search() 接收的参数与 match() 相同,返回字符串中第一个匹配项的索引;如果没有找到,则返回 -1;她会从前往后查找:

var text = "cat,bat,sat,fat";
var pos = text.search(/at/);
console.log(pos);//1


replace() 接收两个参数,第一个参数是字符串或者是 RegExp 对象,第二个参数是一个字符串或者是一个函数。如果第一个参数是字符串,那么就只会替换第一个子字符串,要想替换所有子字符串,必须传入指定全局标志的正则表达式:

var result = text.replace("at", "ond");
console.log(result);//cond,bat,sat,fat

result = text.replace(/at/g, "ond");
console.log(result);//cond,bond,sond,fond


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

字符序列替换文本
$$$
$&匹配整个模式的子字符串(与 RegExp.lastMatch 的值相同)
$’匹配的子字符串之前的子字符串(与 RegExp.leftContext 的值相同)
$`匹配的子字符串之后的子字符串(与 RegExp.rightContext 的值相同)
$n匹配第 n 个捕获组的子字符串。n 为 0 ~ 9。如果正则表达式没有定义捕获组,则使用空字符串
$nn匹配第 nn 个捕获组的子字符串。n 为 01 ~ 99。如果正则表达式没有定义捕获组,则使用空字符串
* 使用特殊的字符序列,可以使用最近一次匹配结果中的内容:

var text = "cat,bat,sat,fat";
result = text.replace(/(.at)/g, "word ($1)");
console.log(result);//word (cat),word (bat),word (sat),word (fat)


replace() 的第二个参数也可以是函数。在只有一个匹配项的情况下,会向这个函数传递 3 个参数:模式的匹配项、模式匹配项在字符串中的位置以及原始字符串。在正则表达式中定义了多个捕获组的情况下,传递给函数的参数依次是模式的匹配项、第一个捕获组的匹配项、第二个捕获组的匹配项……,最后两个参数是模式匹配项在字符串中的位置以及原始字符串。因此这个函数可以实现更加精细的替换操作:

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

console.log(htmlEscape("<p class=\"greeting\">Hello world!</p>"));//<p class="greeting">Hello world!</p>


split() 基于指定的分隔符将一个字符串分割成多个子字符串,并将结果放入数组中。分隔符可以是字符串或者 RegExp 对象。她还接受第二个参数,用于指定数组的大小:

var colorText = "red,blue,green,yellow";
console.log(colorText.split(","));
console.log(colorText.split(",", 2));
console.log(colorText.split(/[^\,]+/));


对 split() 中正则表达式的支持因浏览器而异,因此在使用时,一定要在各种浏览器下做一做测试。

3.7 localeCompare() 方法

比较两个字符串,并返回:

* 如果字符串在字母表中排在字符串参数之前,则返回负数。

* 如果字符串等于字符串参数,则返回 0。

* 如果字符串在字母表中排在字符串参数之后,则返回正数。

var stringValue = "yellow";
console.log(stringValue.localeCompare("brick"));//1
console.log(stringValue.localeCompare("yellow"));//0
console.log(stringValue.localeCompare("zoo"));//-1


因为 localeCompare() 返回的数值取决于实现,因此最好这样使用:

function determineOrder(value) {
var result = stringValue.localeCompare(value);
if (result < 0) {
console.log("The string 'yellow' comes before the string '" + value + "'.");
} else if (result > 0) {
console.log("The string 'yellow' comes after the string '" + value + "'.");
} else {
console.log("The string 'yellow' is equal to the string '" + value + "'.");
}
}
determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");


localeCompare() 所支持的地区决定了这个方法的行为。在美国地区,localeCompare() 是区分大小写的,因此大写字母排在小写字母前是一个决定性的比较规则。其他地区就不一定了,要测试过了才知道哦 O(∩_∩)O~

3.8 fromCharCode() 方法

接收一或者多个字符编码,然后转换为字符串。她是与 charCodeAt() 相反的操作:

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


3.9 HTML 方法

有些浏览器扩展了标准,实现了一些专门用于简化 HTML 格式化任务的方法。最好不要使用,因为它们创建的标记通常无法表达语义,而且不通用,所以这里就不详细列出了哦 O(∩_∩)O~
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: