《JavaScript高级程序设计(第3版)》第5章引用类型总结三

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u010011236/article/details/85997583

5.6、基本包装类型

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

var s1 = 'some text';
var s2 = s1.substring(2);

上述代码在执行第二行代码时,实际会执行如下过程:

// 1.创建 String 类型的一个实例
var s1 = new String('some text');
// 2.在实例上调用指定的方法
var s2 = s1.substring(2);
// 3.销毁这个实例
s1 = null;

总结:引用类型与基本包装类型的主要区别就是对象的生存期。使用 new 操作符创建的引用类型的实例,在执行流离开当前作用域之前都一直保存在内存中。而自动创建的基本包装类型的对象,则只存在于一行代码的执行瞬间,然后立即被销毁。这意味着我们不能在运行时为基本类型值添加属性和方法。

5.6.1、Boolean 类型

Boolean 类型的实例重写了 valueOf() 方法,返回基本类型值 true 或 false;重写了 toString() 方法,返回字符串 "true" 和 "false"。

基本类型与引用类型的布尔值还有两个区别。首先,typeof 操作符对基本类型返回 "boolean",而引用类型返回 "object" 。其次,由于 Boolean 对象是 Boolean 类型的实例,所以使用 instanceof 操作符测试 Boolean 对象会返回 true,而测试基本类型的布尔值则返回 false。

5.6.2、Number 类型

Number 类型重写了 valueOf()、toLocaleString()、toString() 方法。

valueOf() 方法返回对象表示的基本类型的数值,另外两个方法则返回字符串形式的数值。

将数值格式化为字符串的方法:(1)toFixed();(2)toExponential();(3)toPrecision()。

(1)toFixed() 方法

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

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

var num = 10;
console.log(num.toFixed(2)); // '10.00'
var num1 = 10.025;
console.log(num1.toFixed(2)); // '10.03'

(2)toExponential() 方法

toExponential() 方法返回以指数表示法表示的数值的字符串形式。该方法接收一个参数,该参数指定输出结果中的小数位数。

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

(3)toPrecision() 方法

toPrecision() 方法可能返回固定大小(fixed)格式,也可能返回指数(exponential)格式;具体规则是看哪种格式最合适。这个方法接收一个参数,即表示数值的所有数字的位数(不包括指数部分)。

var num2 = 54;
console.log(num2.toPrecision(1)); // '5e+1'
var num3 = 99;
console.log(num3.toPrecision(1)); // '1e+2'

注意:上述三个方法都可以通过向上或向下舍入,做到以最准确的形式来表示带有正确小数位的值。

5.6.3、String 类型

String 对象的方法也可以在所有基本的字符串值中访问到。其中,继承的 valueOf()、toLocaleString() 和 toString() 方法,都返回对象所表示的基本字符串值。

1. 字符方法

charAt() 和 charCodeAt() 返回都接收一个参数,即基于 0 的字符位置。

charAt() 方法以单字符字符串的形式返回给定位置的那个字符。而 charCodeAt() 返回的则是该字符的字符编码。

var stringValue = 'hello world';
console.log(stringValue.charAt(2));     // 'l'
console.log(stringValue.charCodeAt(2)); // 108

2. 字符串操作方法(拼接和截取)

cocat() 方法用于将一个或多个字符串拼接起来,返回拼接得到的新字符串。还可以使用 + 进行字符串的拼接。

ES还提供了三个基于字符串创建新字符串的方法:(1)slice();(2)substr();(3)substring(),且都返回字符串。

slice() 和 substring() 方法的第一个参数指定字符串的开始位置,第二个参数指定的是字符串最后一个字符后面的位置

substr() 方法的第二个参数指定的则是返回的字符个数

如果给上述三个方法指定第二个参数,则将字符串的末尾作为结束位置。

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。

alert(stringValue.slice(-3));    // "rld"
alert(stringValue.substring(-3));// "hello world"
alert(stringValue.substr(-3));   // "rld"
alert(stringValue.slice(3, -4)); // "lo w"
/*
 * stringValue.substring(3, -4) 实际为
 * stringValue.substring(3, 0)
 * 而substring()方法会将较小值的参数作为起始值,所以实际为
 * stringValue.substring(0, 3)
 */
alert(stringValue.substring(3, -4)); // "hel"
alert(stringValue.substr(3, -4)); // ""

3.字符串位置方法

indexOf() 和 lastIndexOf() 都是从一个字符串中搜索给定的子字符串,返回返回字符串的位置(如果没有找到该字符串,则返回-1)。这个两个方法的第二个参数表示搜索的开始位置。

alert(stringValue.indexOf('o'));    // 4
alert(stringValue.lastIndexOf('o'));// 7
alert(stringValue.indexOf('o', 6)); // 7
alert(stringValue.lastIndexOf('o', 6));// 4

// StringTypeLocationMethodsExample02.html
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"

4.trim() 方法

trim() 方法会创建一个字符串副本,删除前置及后缀的所有空格,然后返回结果。

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

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

toLowerCase()、toUpperCase();

toLocaleLowerCase() 和 toLocaleUpperCase() 方法则是针对特定地区的实现。

var stringValue = 'Hello world';
alert(stringValue.toLocaleUpperCase()); // 'HELLO WORLD'
alert(stringValue.toUpperCase());       // 'HELLO WORLD'
alert(stringValue.toLocaleLowerCase()); // 'hello world'
alert(stringValue.toLowerCase());       // 'hello world'

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

match() 方法只接收一个参数,要么是一个正则表达式,要么是一个 RegExp 对象。返回的是一个数组

数组的第一项是与整个模式匹配的字符串,之后的每一项(如果有)保存着与正则表达式中的捕获组匹配的字符串。

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对象) 方法返回字符串中第一个匹配项的索引,如果没有找到匹配项,则返回-1。而且,search() 方法始终是从字符串开头向后查找。

var text = 'cat, bat, sat, fat';
var pos = text.search(/at/);
alert(pos); // 1

replace() 方法接受两个参数:第一个参数可以是 RegExp 对象或者一个字符串(这个字符串不会被转换成正则表达式),第二个参数可以是一个字符串或者一个函数。并返回替换后的字符串

var text = 'cat, bat, sat, fat';

var result = text.replace('at', 'ond');
alert(text);   // 'cat, bat, sat, fat'
alert(result); // 'cond, bat, sat, fat'

result = text.replace(/at/g, 'ond');
alert(result); // 'cond, bond, sond, fond'

var result1 = text.replace(/(.at)/g, 'word ($1)');
alert(result1); // 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 "&lt;"
            case ">":
                return "&gt;";
            case "&":
                return "&amp";
            case "\"":
                return "&quot;";
        }
    });
}
// &lt;p class=&quot;greeting&quot;&gt;hello world!&lt;/p&gt;
alert(htmlEscape("<p class=\"greeting\">hello world!</p>")); 

split() 方法可以基于指定的分割符将一个字符串分割成多个字符串,并将结果放在一个数组中。分隔符可以是字符串,也可以是一个 RegExp 对象(这个方法不会将字符串看成正则表达式)。

var colorText = 'red,blue,green,yellow';
var colors1 = colorText.split(','); // ["red","blue","green","yellow"]
alert(colors1);
var colors2 = colorText.split(',', 2); // ["red","blue"]
alert(colors2);
var colors3 = colorText.split(/[^\,]+/);//["", ",", ",", ",", ""]
alert(colors3);

7.localeCompare() 方法

localeCompare() 方法比较两个字符串,并返回下列值中的一个:

  • 如果字符串在字母表中应该排在传入的字符串参数之前,则返回一个负数(大多数情况下是-1,具体的值要视实现而定);
  • 如果字符串等于传入的字符串参数,则返回0
  • 如果字符串在字母表中应该排在传入的字符串参数之后,则返回一个正数(大多数情况下是1,具体的值同样要视情况而定)。
var stringValue = 'yellow';
alert(stringValue.localeCompare('brick')); // 1
alert(stringValue.localeCompare('yellow'));// 0
alert(stringValue.localeCompare('zoo'));   // -1

// test2
var stringValue = 'yellow';

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');

注意:localeCompare() 方法比较与众不同的地方,就是实现所支持的地区(国家和语言)决定了这个方法的行为。

8.fromCharCode() 方法

fromCharCode() 方法接收一个或多个字符编码,然后将它转换成一个字符串

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

5.7、单体内置对象

ECMA-262对内置对象的定义:“由ECMAScript实现提供的、不依赖于宿主环境的对象,这些对象在ECMAScript程序执行之前就已经存在了。”即开发人员不必显式地实例化内置对象。

5.7.1、Global对象

不属于任何其他对象的属性和方法,最终都是它的属性和方法。例如:所有全局作用域中定义的属性和函数,都是Global 对象的属性。

1.URI编码方法

Global 对象对 URI 进行编码的方法:(1)encodeURI();(2)encodeURIComponent()。即使用 UTF-8 编码替换 URI 中所有无效的字符,让浏览器能够接受和理解。

(1)encodeURI() 不会对本身属于URI的特殊字符进行编码,例如冒号、正斜杠、问好和井号,主要用于整个 URI,与之对应的解码方法为decodeURI()。

(2)encodeURIComponent() 则会对它发现的任何非标准字符进行编码,主要用于对 URI 中的某一段进行编码,与之对应的解码方法为 decodeURIComponent() 。

var url = 'http://www.wrox.com/illegal value.html#start';
//  编码操作
// http://www.wrox.com/illegal%20value.html#start
console.log(encodeURI(url));
// http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.html%23start
console.log(encodeURIComponent(url));

// 解码操作
var encodeUrl = 'http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.html%23start';
console.log(decodeURI(encodeUrl));
console.log(decodeURIComponent(encodeUrl));

2.eval() 方法

eval() 方法只接收一个参数,即要执行的ECMAScript(或JavaScript)字符串。

eval("alert('hi')"); // 等价于 alert('hi');

当解析器发现代码中调用 eval() 方法时,它会将传入的参数当作实际的 ES 语句来解析,然后把执行结果插入到原位置。

3.Global 对象的属性

4.window 对象

Web浏览器都是将这个全局对象(Global)作为 window 对象的一部分加以实现的。因此,在全局作用域中声明的所有变量和函数,就都成为了 window 对象的属性。

var color = 'red';

function sayColor() {
    alert(window.color);
}

window.sayColor();  // 'red'

另一种取得 Global 对象的方法:

var global = function() {
    return this;
}();

5.7.2、Math 对象

1.Math 对象的属性

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

要找到数组中的最大值或最小值,可以如下所示:

var values = [1, 2, 3, 4, 5, 6, 7, 8];
var max = Math.max.apply(Math, values);

3.舍入方法

  • Math.ceil() 执行向上舍入,即它总是将数值向上舍入为最接近的整数;
  • Math.floor() 执行向下舍入,即它总是将数值向下舍入为最接近的整数;
  • Math.round() 执行标准舍入,即它总是将数值四舍五入为最接近的整数(这也是我们在数学课上学到的舍入规则)。
alert(Math.ceil(25.9));     // 26
alert(Math.ceil(25.5));     // 26
alert(Math.ceil(25.1));     // 26

alert(Math.round(25.9));    // 26
alert(Math.round(25.5));    // 26
alert(Math.round(25.1));    // 25

alert(Math.floor(25.9));    // 25
alert(Math.floor(25.5));    // 25
alert(Math.floor(25.1));    // 25

4.random() 方法

Math.random() 方法返回大于等于 0 小于 1 的一个随机数。计算公式如下所示:

值 = Math.floor( Math.random() * 可能值的总数 + 第一个可能的值 );

// 选择一个 1 到 10 之间的数值
var num = Math.floor(Math.random() * 10 + 1);
alert(num);

// 选择一个介于 2 到 10 之间的值
// 方式一
var num1 = Math.floor(Math.random() * 9 + 2);
alert(num1);

// 方式二
function selectFrom(lowerValue, upperValue) {
    var choices = upperValue - lowerValue + 1;
    return Math.floor(Math.random() * choices + lowerValue);
}

var num2 = selectFrom(2, 10);
alert(num2);

var colors = ['red', 'green', 'blue', 'yellow', 'black', 'purple', 'brown'];
var color = colors[selectFrom(0, colors.length - 1)];
alert(color);   // 可能是数组中包含的任何一个字符串

5.其他方法

参考文献

[1]《JavaScript高级程序设计(第3版)》

猜你喜欢

转载自blog.csdn.net/u010011236/article/details/85997583