JavaScript高级程序设计(第三版)5章

2018-10-11  本文已影响0人  ft207741

Menu


第5章 引用类型

5.1 Object类型
// 第一种是使用 new 操作符后跟 Object 构造函数
var person = new Object();
person.name = "Nicholas";
person.age = 29;
// 另一种方式是使用对象字面量表示法。
var person = {
name : "Nicholas",
age : 29
};
alert(person["name"]); //"Nicholas"
alert(person.name); //"Nicholas"

5.2 Array类型

var colors = new Array("red", "blue", "green");  // 1. 构造函数创建
var colors = ["red", "blue", "green"];  // 2. 使用数组字面量表示法
var values = ["red", "orange", "yellow"];  //创建字面量Array
values[3] = "green";  // 增加数组长度
values.length = 2;   // 调节array的长度;
document.write(values[3])  // 输出 undefined;
var colors = ["red", "orange", "yellow"]; // 创建一个包含 3 个字符串的数组
colors[colors.length] = "green"; //(在位置 3)添加一种颜色
colors[colors.length] = "cyan"; //(在位置 4)再添加一种颜色
colors.push("blue")  // 用Array方法在末尾添加item
// 检测是否是Array的实例;
if (Array.isArray(value)){
    // do_something
}
// 检测是否是Array;
if(some_variable instanceof Array){
    // do something;
}
// 升序排序函数;降序-1 和 1互换位置即可;
   function compare(value1, value2) {
        if (value1 < value2) {
            return -1;       // -1 靠前排一位
        } else if (value1 > value2) {
            return 1;       // -1 靠后排一位
        } else {
            return 0;
        }
    }

   list.sort(compare)
   document.write(list)
    list = [15, 11, 1, 6, 90];
    function compare(value1, value2){
        return value1 - value2;
    }
    document.write(list.sort(compare))
var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow", ["black", "brown"]);
alert(colors2); //red,green,blue,yellow,black,brown
var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);  // 相当于python的 clolrs[1:]
var colors3 = colors.slice(1,4);   // 相当于python的 clolrs[1:4]
alert(colors2); //green,blue,yellow,purple
alert(colors3); //green,blue,yellow
Array.splice(0, 2)     // 参数1是:下标, 参数2是删除n项;
    list = [15, 11, 1, 6, 90];
    list.splice(0, 0, "a", "b")   // 插入到下表0, 不删除原有项,插入item
    document.write(list) // a,b,15,11,1,6,90
    list = [15, 11, 1, 6, 90];
    list.splice(0, 1, "a", "b")   // 插入到下表0, 删除原有项,插入item
    document.write(list) // a,b,15,11,1,6,90
function f(n) {
    return n ** 2
}
var n = [0, 1, 2, 3, 4, 5, 6]
document.write(n.map(f))  // 0,1,4,9,16,25,36
    var numbers = [1,2,3,4,5,4,3,2,1];
    var filterResult = numbers.filter(function(item, index, array){
        return (item > 2);
    });
    alert(filterResult); //[3,4,5,4,3]
var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
  return prev + cur;
  });
alert(sum); //15

var someDate = new Date(Date.parse("May 25, 2004"));
// Tue May 25 2004 00:00:00 GMT+0800 
var someDate = new Date("May 25, 2004");
// GMT 时间 2000 年 1 月 1 日午夜零时
var y2k = new Date(Date.UTC(2000, 0));

// GMT 时间 2005 年 5 月 5 日下午 5:55:55
var allFives = new Date(Date.UTC(2005, 4, 5, 17, 55, 55));

// 构造函数Date也会模仿Date.UTC()方法来达到同样的效果:
// 本地时间 2000 年 1 月 1 日午夜零时
var y2k = new Date(2000, 0);

// 本地时间 2005 年 5 月 5 日下午 5:55:55
var allFives = new Date(2005, 4, 5, 17, 55, 55);

5.4 RegExp 类型
    //  匹配所有.at的字符,不区分大小写
    var re_exp = /.at/gi;
    while(true){
        re = re_exp.exec("asdfat..at;;;AtasdAt")
        if (re==null){break}
        document.write(re)  // fat.at;AtdAt 
    }
    //  通过RegExp Object构造函数创建匹配所有.at的字符,不区分大小写
    var re_exp = new RegExp(".at", "gi");
    while(true){
        re = re_exp.exec("asdfat..at;;;AtasdAt");
        if (re==null){break;}
        document.write(re);  // fat.at;AtdAt
    }
    var re_exp = new RegExp(".(at)", "gi");
    while(true){
        re = re_exp.exec("asdfat..at;;;AtasdAt");
        if (re==null){break;}
        document.write("匹配项->[{0}]捕获组->[{1}]".format(re[0],re[1]),"<br>");   // js没有format,需要自己写;
    }
    // 匹配项->[fat]捕获组->[at]
    // 匹配项->[.at]捕获组->[at]
    // 匹配项->[;At]捕获组->[At]
    // 匹配项->[dAt]捕获组->[At]
var pattern2 = /.at/g;
var matches = pattern2.exec(text);
alert(matches.index); //0
alert(matches[0]); //cat
alert(pattern2.lastIndex); //3

matches = pattern2.exec(text);
alert(matches.index); //5
alert(matches[0]); //bat
alert(pattern2.lastIndex); //8
var text = "000-00-0000";
var pattern = /\d{3}-\d{2}-\d{4}/;
if (pattern.test(text)){
alert("The pattern was matched.");
}
var pattern = new RegExp("\\[bc\\]at", "gi");
alert(pattern.toString()); // /\[bc\]at/gi
alert(pattern.toLocaleString()); // /\[bc\]at/gi

例子:

var text = "this has been a short summer";
var pattern = /(.)hort/g;
/*
* 注意: Opera 不支持 input、 lastMatch、 lastParen 和 multiline 属性
* Internet Explorer 不支持 multiline 属性
*/
    if (pattern.test(text)){
        document.write(RegExp.input, "<br>"); // this has been a short summer
        document.write(RegExp.leftContext, "<br>"); // this has been a
        document.write(RegExp.rightContext, "<br>"); // summer
        document.write(RegExp.lastMatch, "<br>"); // short
        document.write(RegExp.lastParen, "<br>"); // s
        document.write(RegExp.multiline, "<br>"); // firefox display: undefined
    }
var text = "this has been a short summer";
var pattern = /(.)hort/g;

if (pattern.test(text)){
alert(RegExp.$_); // this has been a short summer
alert(RegExp["$`"]); // this has been a
alert(RegExp["$'"]); // summer
alert(RegExp["$&"]); // short
alert(RegExp["$+"]); // s
alert(RegExp["$*"]);  // firefox display: undefined
}
/*RegExp.$1
RegExp.$2
…
RegExp.$9*/

var text = "this has been a short summer";
var pattern = /(..)or(.)/g;
if (pattern.test(text)){
alert(RegExp.$1); //sh
alert(RegExp.$2); //t
}

5.5 函数类型
    function callSomeFunction(someFunction, someArgument){
        return someFunction(someArgument);
    }
    function add10(num){
        return num + 10;
    }
    var result1 = callSomeFunction(add10, 10);
    document.write(result1); //20

    function getGreeting(name){
        return "Hello, " + name;
    }
    var result2 = callSomeFunction(getGreeting, "Nicholas");
    document.write(result2); //"Hello, Nicholas"
    //紧密耦合:
    function factorial(num){
        if (num <=1) {
            return 1;
        } else {
            return num * factorial(num-1)
        }
    }
    document.write(factorial(5)) // 120
    //改良后, 函数名可以改变:
    function factorial(num){
        if (num <=1) {
            return 1;
        } else {
            return num * arguments.callee(num-1)
        }
    }
    var trueFactorial = factorial;
    factorial = function(){
        return 0;
    };
     document.write(trueFactorial(5)); //120
     document.write(factorial(5)); //0
    window.color = "red";
    var o = { color: "blue" };
    function sayColor(){
        document.write(this.color);
    }
    sayColor(); //"red"
    o.sayColor = sayColor;
    o.sayColor(); //"blue"
    function outer(){
        inner();
    }
    function inner(){
        alert(inner.caller);
    }
    outer(); //function outer(){inner();} 
    //结果为显示 outer()函数的源代码, 因为是 outer()调用了 inter();
    function outer(){
        inner();
    }
    function inner(){
        alert(arguments.callee.caller); //用arguments.callee.caller实现更松散的耦合;
    }
    outer(); //结果同上
//第二个参数可以是 Array 的实例,也可以是
arguments 对象。
    function sum(num1, num2){
        return num1 + num2;
    }
    function callSum1(num1, num2){
        return sum.apply(this, arguments); // 传入 arguments 对象
    }
    function callSum2(num1, num2){
        return sum.apply(this, [num1, num2]); // 传入数组
    }
    document.write(callSum1(10,10)); //20
    document.write(callSum2(10,10)); //20
    function sum(num1, num2){
        return num1 + num2;
    }
    function callSum(num1, num2){
        return sum.call(this, num1, num2);
    }
    document.write(callSum(10,10)); //20
    window.color = "red";
    var o = { color: "blue" };
    function sayColor(){
        document.write(this.color);
    }
    sayColor(); //red
    sayColor.call(this); //red
    sayColor.call(window); //red
    sayColor.call(o); //blue
    window.color = "red";
    var o = { color: "blue" };
    function sayColor(){
        document.write(this.color);
    }
    var objectSayColor = sayColor.bind(o);
    objectSayColor(); //blue
5.6 基本包装类型
    var s1 = "some text";
    s1.color = "red";
    document.write(s1.color); //undefined
    var value = "25";
    var number = Number(value); //转型函数
    document.write(typeof number); //"number"
    var obj = new Number(value); //构造函数
    document.write(typeof obj); //"object"
    //变量 number 中保存的是基本类型的值 25
    //变量 obj 中保存的是 Number 的实例
var booleanObject = new Boolean(true)
    var falseObject = new Boolean(false);
    var result = falseObject && true;
    document.write(result); //true;布尔表达式中的所有对象都会被转换为 true;
    var falseValue = false;
    result = falseValue && true;
    document.write(result); //false
var stringValue = "hello world";
alert(stringValue.charAt(1)); //"e"
alert(stringValue.charCodeAt(1)); //输出"101"
var stringValue = "hello ";
var result = stringValue.concat("world", "!");
alert(result); //"hello world!"
alert(stringValue); //"hello"
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"
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)); //""(空字符串)
var stringValue = " hello world ";
var trimmedStringValue = stringValue.trim();
alert(stringValue); //" hello world "
alert(trimmedStringValue); //"hello world"
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
var text = "cat, bat, sat, fat";
var pos = text.search(/at/);
alert(pos); //1
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.leftContext的值相同
$` : 匹配的子字符串之后的子字符串。与RegExp.rightContext的值相同
$n :匹配第n个捕获组的子字符串,其中n等于0~9。例如, $1是匹配第一个捕获组的子字符串, $2是匹配第二个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串
$nn :匹配第nn个捕获组的子字符串,其中nn等于01~99。例如, $01是匹配第一个捕获组的子字符串, $02:是匹配第二个捕获组的子字符串,以此类推。如果正则表达式中没有定义捕获组,则使用空字符串
\\通过这些特殊的字符序列,可以使用最近一次匹配结果中的内容,如下面的例子所示。
var text = "cat, bat, sat, fat";
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;";
            }
        });
    }
    document.write(htmlEscape("<p class=\"greeting\">Hello world!</p>"));
    //&lt;p class=&quot;greeting&quot;&gt;Hello world!&lt;/p&gt;
    var colorText = "red,blue,green,yellow";
    var colors1 = colorText.split(","); //["red", "blue", "green", "yellow"]
    var colors2 = colorText.split(",", 2); //["red", "blue"]
    var colors3 = colorText.split(/[^\,]+/); //["", ",", ",", ",", ""]
var stringValue = "yellow";
alert(stringValue.localeCompare("brick")); //1
alert(stringValue.localeCompare("yellow")); //0
alert(stringValue.localeCompare("zoo")); //-1
    var stringValue = "yellow";
    function determineOrder(value) {
        var result = stringValue.localeCompare(value);
        if (result < 0){
            document.write("The string 'yellow' comes before the string '" + value + "'.");
        }
        else if (result > 0) {
            document.write("The string 'yellow' comes after the string '" + value + "'.");
        }
        else {
            document.write("The string 'yellow' is equal to the string '" + value + "'.");
        }
    }
    determineOrder("brick");//The string 'yellow' comes after the string 'brick'.
    determineOrder("yellow");//The string 'yellow' is equal to the string 'yellow'.
    determineOrder("zoo");//The string 'yellow' comes before the string 'zoo'. 
alert(String.fromCharCode(104, 101, 108, 108, 111)); //"hello"
    var uri = "http://www.wrox.com/illegal value.htm#start";
    //"http://www.wrox.com/illegal%20value.htm#start"
    //只有空格被替换成了%20。
    document.write(encodeURI(uri));
    //"http%3A%2F%2Fwww.wrox.com%2Fillegal%20value.htm%23start"
    //替换了所有非字母数字字符
    document.write(encodeURIComponent(uri));
eval("alert('hi')");
//这行代码的作用等价于下面这行代码:
alert("hi");

eval("function sayHi() { alert('hi'); }");
sayHi(); //hi

eval("var msg = 'hello world'; ");
document.write(msg); //"hello world"
  1. window 对象:全局作用域中声明的所有变量和函数,都是 window对象的属性。
var color = "red";
function sayColor(){
alert(window.color);
}
window.sayColor(); //"red"
    //另一种取得 Global 对象的方法
    var global = function(){
        return this;
    }();
    var max = Math.max(3, 54, 32, 16);
    document.write(max); //54
    var min = Math.min(3, 54, 32, 16);
    document.write(min); //3
    var values = [1, 2, 3, 4, 5, 6, 7, 8];
    var max = Math.max.apply(Math, values);
    var max2 = Math.max(values)
    document.write(max) // 8
    document.write(max2)  //NaN
    document.write(Math.ceil(25.9)); //26
    document.write(Math.ceil(25.5)); //26
    document.write(Math.ceil(25.1)); //26

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

    document.write(Math.floor(25.9)); //25
    document.write(Math.floor(25.5)); //25
    document.write(Math.floor(25.1)); //25
值 = Math.floor(Math.random() * 可能值的总数 + 第一个可能的值)
//如果你想选择一个 1到 10 之间的数值:
var num = Math.floor(Math.random() * 10 + 1);
//如果想要选择一个介于 2 到 10 之间的值:
var num = Math.floor(Math.random() * 9 + 2);//从 2 数到 10 要数 9 个数,因此可能值的总数就是 9,而第一个可能的值就是 2。
    function selectFrom(lowerValue, upperValue) {
        var choices = upperValue - lowerValue + 1;
        return Math.floor(Math.random() * choices + lowerValue);
    }
    var num = selectFrom(2, 10);
    document.write(num); // 介于 2 和 10 之间(包括 2 和 10)的一个数值

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

page 146 /153 没看懂

    function selectFrom(lowerValue, upperValue) {
        var choices = upperValue - lowerValue + 1;
        return Math.floor(Math.random() * choices + lowerValue);
    }
    var num = selectFrom(2, 10);
    document.write(num); // 介于 2 和 10 之间(包括 2 和 10)的一个数值
上一篇 下一篇

猜你喜欢

热点阅读