本节目录
- 一、Number类型
- 1.1 toString() 方法 ---- 设置进制
- 1.2 toFixed() 方法 ---- 小数点后位数
- 1.3 toExponential() 方法 ---- 指数表示
- 1.4 toPrecision() 方法 ---- 自动匹配是否用指数
- 二、Math 对象
- 2.1 Math 对象的属性
- 2.2 min() 和 max() 方法
- 2.3 Math.ceil() ---- 向上舍入
- 2.4 Math.floor() ---- 向下舍入
- 2.5 Math.round() ---- 四舍五入
- 2.6 random() 方法 ---- 生成随机数
- 2.7 其他方法
- 三、String类型
一、Number类型
1.1 toString() 方法 ---- 设置进制
var num = 10;
alert(num.toString()); //"10"
alert(num.toString(2)); //"1010"
alert(num.toString(8)); //"12"
alert(num.toString(10)); //"10"
alert(num.toString(16)); //"a"
1.2 toFixed() 方法 ---- 小数点后位数
toFixed()方法会按照指定的小数位返回数值的字符串表示:
var num = 10;
alert(num.toFixed(2)); //"10.00"
如果数值本身包含的小数位比指定的还多,那么接近指定的最大小数位的值就会舍入,如下面的例子所示:
var num = 10.005;
alert(num.toFixed(2)); //"10.01"
能够自动舍入的特性,使得 toFixed()方法很适合处理货币值。
1.3 toExponential() 方法 ---- 指数表示
该方法返回以指数表示法(也称 e 表示法)表示的数值的字符串形式。与 toFixed()一样,toExponential()也接收一个参数,而且该参数同样也是指定输出结果中的小数位数。看下面的例子:
var num = 10;
alert(num.toExponential(1)); //"1.0e+1"
1.4 toPrecision() 方法 ---- 自动匹配是否用指数
var num = 99;
alert(num.toPrecision(1)); //"1e+2"
alert(num.toPrecision(2)); //"99"
alert(num.toPrecision(3)); //"99.0"
以上代码首先完成的任务是以一位数来表示 99,结果是 “1e+2”,即 100。因为一位数无法准确地表示 99,因此 toPrecision()就将它向上舍入为 100,这样就可以使用一位数来表示它了。
而接下来的用两位数表示 99,当然还是"99"。
最后,在想以三位数表示 99 时,toPrecision()方法返了"99.0"。
实际上,toPrecision()会根据要处理的数值决定到底是调用 toFixed()还是调用 toExponential()。
而这三个方法都可以通过向上或向下舍入,做到以最准确的形式来表示带有正确小数位的值。
二、Math 对象
2.1 Math 对象的属性
这些属性都是一些特殊值:
2.2 min() 和 max() 方法
min()和 max()方法用于确定一组数值中的最小值和最大值。这两个方法都可以接收任意多个数值参数,如下面的例子所示:
var max = Math.max(3, 54, 32, 16);
alert(max); //54
var min = Math.min(3, 54, 32, 16);
alert(min); //3
配合 apply() 方法 比较数组数值:
var values = [1, 2, 3, 4, 5, 6, 7, 8];
var max = Math.max.apply(Math, values);
这个技巧的关键是把 Math 对象作为 apply()的第一个参数,从而正确地设置 this 值。然后,可以将任何数组作为第二个参数。
2.3 Math.ceil() ---- 向上舍入
alert(Math.ceil(25.9)); //26
alert(Math.ceil(25.5)); //26
alert(Math.ceil(25.1)); //26
2.4 Math.floor() ---- 向下舍入
alert(Math.floor(25.9)); //25
alert(Math.floor(25.5)); //25
alert(Math.floor(25.1)); //25
2.5 Math.round() ---- 四舍五入
alert(Math.round(25.9)); //26
alert(Math.round(25.5)); //26
alert(Math.round(25.1)); //25
2.6 random() 方法 ---- 生成随机数
Math.random()方法返回大于等于 0 小于 1 的一个随机数。
对于某些站点来说,这个方法非常实用,因为可以利用它来随机显示一些名人名言和新闻事件。套用下面的公式,就可以利用 Math.random() 从某个整数范围内随机选择一个值。
值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值)
公式中用到了 Math.floor()方法,这是因为 Math.random() 总返回一个小数值。而用这个小数值乘以一个整数,然后再加上一个整数,最终结果仍然还是一个小数。举例来说,如果你想选择一个 1 到 10 之间的数值,可以像下面这样编写代码:
var num = Math.floor(Math.random() * 10 + 1);
而如果想要选择一个介于 2 到 10 之间的值,就应该将上面的代码改成这样:
var num = Math.floor(Math.random() * 9 + 2);
多数情况下,其实都可以通过一个函数来计算可能值的总数和第一个可能的值,例如:
function selectFrom(lowerValue, upperValue) {
var choices = upperValue - lowerValue + 1;
return Math.floor(Math.random() * choices + lowerValue);
}
var num = selectFrom(2, 10);
alert(num); // 介于 2 和 10 之间(包括 2 和 10)的一个数值
利用上面这个函数,可以方便地从数组中随机取出一项,例如:
var colors = ["red", "green", "blue", "yellow", "black", "purple", "brown"];
var color = colors[selectFrom(0, colors.length-1)];
alert(color); // 可能是数组中包含的任何一个字符串
2.7 其他方法
下面我们就给出一个表格,列出上面没有介绍到的 Math 对象的方法:
方 法 | 说 明 |
---|---|
Math.abs(num) | 返回num 的绝对值 |
Math.sqrt(num) | 返回num 的平方根 |
Math.log(num) | 返回num 的自然对数 |
Math.exp(num) | 返回Math.E 的num 次幂 |
Math.pow(num,power) | 返回num 的power 次幂 |
Math.tan(x) | 返回x 的正切值 |
Math.sin(x) | 返回x 的正弦值 |
Math.cos(x) | 返回x 的余弦值 |
Math.acos(x) | 返回x 的反余弦值 |
Math.atan(x) | 返回x 的反正切值 |
Math.asin(x) | 返回x 的反正弦值 |
Math.atan2(y,x) | 返回 y/x 的反正切值 |
三、String类型
3.1 String 类型简介
字符串可以由双引号(")或单引号(’)表示,用双引号表示的字符串和用单引号表示的字符串完全相同。不过,以双引号开头的字符串也必须以双引号结尾,而以单引号开头的字符串必须以单引号结尾:
var firstName = "Nicholas";
var lastName = 'Zakas';
var firstName = 'Nicholas"; // 语法错误(左右引号必须匹配)
3.1.1 字符字面量/转义序列
方法 | 作用 |
---|---|
\n | 换行 |
\t | 制表 |
\b | 空格 |
\r | 回车 |
\f | 进纸 |
\ | 斜杠 |
’ | 单引号(’),在用单引号表示的字符串中使用。例如:‘He said, \‘hey.\’’ |
" | 双引号("),在用双引号表示的字符串中使用。例如:“He said, \“hey.\”” |
\xnn | 以十六进制代码nn表示的一个字符(其中n为0~F)。例如,\x41表示"A" |
\unnnn | 以十六进制代码nnnn表示的一个Unicode字符(其中n为0~F)。例如,\u03a3表示希腊字符Σ |
3.1.2 字符串拼接的过程
var lang = "Java";
lang = lang + "Script"; // "JavaScript"
实现这个操作的过程如下:首先创建一个能容纳 10 个字符的新字符串,然后在这个字符串中填充 “Java” 和 “Script”,最后一步是销毁原来的字符串 “Java” 和字符串 “Script” ,因为这两个字符串已经没用了。
这个过程是在后台发生的,而这也是在某些旧版本的浏览器(例如版本低于 1.0 的 Firefox、IE6 等)中拼接字符串时速度很慢的原因所在。但这些浏览器后来的版本已经解决了这个低效率问题。
3.2 字符方法
3.2.1 charAt() 方法 ---- 返回给定位置字符
charAt() 方法以单字符字符串的形式返回给定位置的字符(ECMAScript 中没有字符类型)。例如:
var stringValue = "hello world";
alert(stringValue.charAt(1)); //"e"
字符串"hello world"位置 1 处的字符是"e",因此调用 charAt(1)就返回了"e"。
3.2.2 charCodeAt() 方法 ---- 得到字符编码
charCodeAt() 方法得到的是字符编码。
var stringValue = "hello world";
alert(stringValue.charCodeAt(1)); //输出"101"
这个例子输出的是"101",也就是小写字母"e"的字符编码。
3.2.3 方括号加数字索引 [num]
ECMAScript 5 还定义了另一个访问个别字符的方法。在支持此方法的浏览器中,可以使用方括号加数字索引来访问字符串中的特定字符,如下面的例子所示。
var stringValue = "hello world";
alert(stringValue[1]); //"e"
使用方括号表示法访问个别字符的语法得到了 IE8 及 Firefox、Safari、Chrome 和 Opera 所有版本的支持。如果是在 IE7 及更早版本中使用这种语法,会返回 undefined 值(尽管根本不是特殊的 undefined 值)。
3.3 字符串操作方法
下面介绍的 concat() 、slice() 、substr() 和 substring() 方法不会修改字符串本身的值——它们只是返回一个基本类型的字符串值,对原始字符串没有任何影响。
3.3.1 concat() 方法 =(+)---- 拼接字符串
concat() 方法用于将一或多个字符串拼接起来,返回拼接得到的新字符串。
var stringValue = "hello ";
var result = stringValue.concat("world");
alert(result); //"hello world"
alert(stringValue); //"hello"
在这个例子中,通过 stringValue 调用 concat() 方法返回的结果是"hello world"——但 stringValue 的值则保持不变。实际上,concat()方法可以接受任意多个参数,也就是说可以通过它拼接任意多个字符串。再看一个例子:
var stringValue = "hello ";
var result = stringValue.concat("world", "!");
alert(result); //"hello world!"
alert(stringValue); //"hello"
实践中使用更多的还是加号操作符(+)。因为使用加号操作符在大多数情况下都比使用concat()方法要简便易行。
3.3.2 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"
如果参数是负值:
- 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)); //""(空字符串)
这里 substring() 方法会把第二个参数转换为 0,使调用变成了 substring(3,0),而由于这个方法会将较小的数作为开始位置,将较大的数作为结束位置,因此最终相当于调用了 substring(0,3)。
substr()也会将第二个参数转换为 0,这也就意味着返回包含零个字符的字符串,也就是一个空字符串。
3.3.3 toLowerCase() 和 toUpperCase() 方法 ---- 大小写转换
var stringValue = "hello world";
alert(stringValue.toLocaleUpperCase()); //"HELLO WORLD"
alert(stringValue.toUpperCase()); //"HELLO WORLD"
alert(stringValue.toLocaleLowerCase()); //"hello world"
alert(stringValue.toLowerCase()); //"hello world"
3.4 字符串位置方法
3.4.1 indexOf() 和 lastIndexOf() 方法 ---- 查找子字符串
indexOf()方法从字符串的开头向后搜索子字符串(如果没有找到,则返回 -1)。
lastIndexOf()方法是从字符串的末尾向前搜索子字符串。(如果没有找到,则返回 -1)。
如果要搜索的子字符串在字符串中只有一个,那么 indexOf()方法和 lastIndexOf()方法搜索的结果一样。
var stringValue = "hello world";
alert(stringValue.indexOf("o")); //4
alert(stringValue.lastIndexOf("o")); //7
这两个方法都可以接收可选的第二个参数,表示从字符串中的哪个位置开始搜索。
indexOf()会从该参数指定的位置向后搜索,忽略该位置之前的所有字符。
lastIndexOf()则会从指定的位置向前搜索,忽略该位置之后的所有字符。
var stringValue = "hello world";
alert(stringValue.indexOf("o", 6)); //7
alert(stringValue.lastIndexOf("o", 6)); //4
遍历查找示例:
var stringValue = "Lorem ipsum dolor sit amet, consectetur adipisicing elit";
var positions = new Array();
var pos = stringValue.indexOf("e");
while(pos > -1){
positions.push(pos);
pos = stringValue.indexOf("e", pos + 1);
}
alert(positions); //"3,24,32,35,52"
3.4.2 trim() 方法 ---- 删除字符串前后空格
var stringValue = " hello world ";
var trimmedStringValue = stringValue.trim();
alert(stringValue); //" hello world "
alert(trimmedStringValue); //"hello world"
由于 trim()返回的是字符串的副本,所以原始字符串中的前置及后缀空格会保持不变。支持这个方法的浏览器有 IE9+、Firefox 3.5+、Safari 5+、Opera 10.5+和 Chrome。此外,Firefox 3.5+、Safari 5+和 Chrome 8+还支持非标准的 trimLeft()和 trimRight()方法,分别用于删除字符串开头和末尾的空格。
3.5 字符串查找
3.5.1 match() 方法 ---- 返回匹配值
match() 方法本质上与调用 RegExp 的 exec()方法相同。match()方法只接受一个参数,要么是一个正则表达式,要么是一个 RegExp 对象。
var text = "cat, bat, sat, fat";
var pattern = /.at/;
//与 pattern.exec(text)相同
// ---- var matches = pattern.exec(text);
var matches = text.match(pattern);
alert(matches.index); //0
alert(matches[0]); //"cat"
alert(pattern.lastIndex); //0
3.5.2 search() 方法 ---- 查找字符串位置
search()方法返回字符串中第一个匹配项的索引(位置);如果没有找到匹配项,则返回-1。而且,search()方法始终是从字符串开头向后查找模式。
var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
alert(pos); //1
3.5.3 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"
特殊的字符序列
举个例子:
var text = "cat, bat, sat, fat";
result = text.replace(/(.at)/g, "word ($1)");
alert(result); //word (cat), word (bat), word (sat), word (fat)
3.5.4 split() 方法 ---- 分隔字符串
这个方法可以基于指定的分隔符将一个字符串分割成多个子字符串,并将结果放在一个数组中。
split()方法可以接受可选的第二个参数,用于指定数组的大小。
var colorText = "red,blue,green,yellow";
var colors1 = colorText.split(","); //["red", "blue", "green", "yellow"]
var colors2 = colorText.split(",", 2); //["red", "blue"]
3.5.5 localeCompare() 方法 ---- 比较字符串
这个方法比较两个字符串,并返回下列值中的一个:
- 如果字符串在字母表中应该排在字符串参数之前,则返回一个负数(大多数情况下是-1,具体的值要视实现而定);
- 如果字符串等于字符串参数,则返回 0;
- 如果字符串在字母表中应该排在字符串参数之后,则返回一个正数(大多数情况下是 1,具体的值同样要视实现而定)。
下面是几个例子。
var stringValue = "yellow";
alert(stringValue.localeCompare("brick")); //1
alert(stringValue.localeCompare("yellow")); //0
alert(stringValue.localeCompare("zoo")); //-1
使用 localeCompare() 实现功能的例子:
function determineOrder(value) {
var result = stringValue.localeCompare(value);
if (result < 0){
alert("The string 'yellow' comes before the string '" + value + "'.");
} else if (result > 0) {
alert("The string 'yellow' comes after the string '" + value + "'.");
} else {
alert("The string 'yellow' is equal to the string '" + value + "'.");
}
}
determineOrder("brick");
determineOrder("yellow");
determineOrder("zoo");
3.5.6 fromCharCode() 方法 ---- 编码转换字符串
String 构造函数本身还有一个静态方法:fromCharCode()。
这个方法的任务是接收一或多个字符编码,然后将它们转换成一个字符串。从本质上来看,这个方法与实例方法 charCodeAt() 执行的是相反的操作。
来看一个例子:
alert(String.fromCharCode(104, 101, 108, 108, 111)); //"hello"