關於JavaScript的學習(五)——引用類型

第五章

  • Object類型
var person = new Object();  //或 var person={};
person.name = "Nicholas";
person.age = 29;

//與上面相同,爲對象字面量表示法
var person = {
    name : "Nicholas",
    age : 29
}

alert(person["name"]);        //"Nicholas"
alert(person.name);           //"Nicholas"
var propertyName = "name";
alert(person[propertyName]);  //"Nicholas"
//建議用點表示法
  • Array類型
var colors = ["red","blue","green"];
alert(colors.length);     //3

#length長度可以設置
var colors = ["red","blue","green"];
colors.length = 2;
alert(colors[2]);    //undefined

#toLocaleString()和toString()
var person1 = {
    toLocaleString : function () {
        return "Nikolaos";
    },

    toString : function() {
        return "Nicholas";
    }
};
var person2 = {
    toLocaleString : function () {
        return "Grigorios";
    },

    toString : function() {
        return "Greg";
    }
};
var people = [person1, person2];
alert(people);                      //Nicholas,Greg
alert(people.toString());           //Nicholas,Greg
alert(people.toLocaleString());     //Nikolaos,Grigorios

#join()
var colors = ["red", "green", "blue"];
alert(colors.join(",")); //red,green,blue
alert(colors.join("||")); //red||green||blue

#push()和pop()   棧方法
var colors = new Array(); //create an array
var count = colors.push("red", "green"); //push two items
alert(count);  //2
count = colors.push("black");//push another item on
alert(count);  //3
var item = colors.pop();//get the last item
alert(item);   //"black"
alert(colors.length);  //2

#shift()和unshift()     隊列方法
var colors = new Array(); //create an array
var count = colors.push("red", "green");  //push two items
alert(count);  //2
count = colors.push("black");  //push another item on
alert(count);  //3
var item = colors.shift(); //get the first item
alert(item);   //"red"
alert(colors.length);  //2

var colors = new Array();    //create an array
var count = colors.unshift("red", "green");    //push two items
alert(count);  //2
count = colors.unshift("black"); //push another item on
alert(count);  //3
var item = colors.pop();  //get the first item
alert(item);   //"green"
alert(colors.length);  //2

#resverse()和sort()   重排序方法
var values = [1, 2, 3, 4, 5];
values.reverse();
alert(values);       //5,4,3,2,1

function compare(value1, value2) {
    if (value1 < value2) {
        return 1;
    } else if (value1 > value2) {
        return -1;
    } else {
        return 0;
    }
}
var values = [0, 1, 5, 10, 15];
values.sort(compare);
alert(values);    //15,10,5,1,0

//或將compare改爲
function compare(value1, value2) {
    return value2-value1;
}

#concat()
var colors = ["red", "green", "blue"];
var colors2 = colors.concat("yellow", ["black", "brown"]);
alert(colors);     //red,green,blue        
alert(colors2);    //red,green,blue,yellow,black,brown

#slice()
//只有一個參數的情況,slice返回從該參數指定位置開始到當前數組末尾的左右項
//如果有兩個參數,該方返回起始和結束位置之間的項——但不包括結束位置的項
var colors = ["red", "green", "blue", "yellow", "purple"];
var colors2 = colors.slice(1);
var colors3 = colors.slice(1,4);
alert(colors2);   //green,blue,yellow,purple
alert(colors3);   //green,blue,yellow

#splice()
/*刪除:刪除任意數量的項,2個參數:要刪除的第一項的位置、要刪除的項數
 *插入:向指定位置插入任意數量的項,3個參數:起始位置、0、要插入的項數
 *替換:向指定位置插入任意數量的項,3個參數:起始位置、要刪除的項數、要插入的任意數量的項
 *始終會返回一個數組,數組中包含從原始數組中刪除的項(如果沒有則返回空數組)
 */
var colors = ["red", "green", "blue"];
var removed = colors.splice(0,1); //刪除第一項
alert(colors); //green,blue
alert(removed);  //red,返回的數組中只包含一項

removed = colors.splice(1, 0, "yellow", "orange");  //從位置1開始插入兩項
alert(colors); //green,yellow,orange,blue
alert(removed); //返回空數組

removed = colors.splice(1, 1, "red", "purple"); //插入兩項,刪除一項
alert(colors); //green,red,purple,orange,blue
alert(removed); //yellow,返回的數組中只包含一項

#indexOf()和lastIndexOf()      位置方法
var numbers = [1,2,3,4,5,4,3,2,1];
alert(numbers.indexOf(4));        //3
alert(numbers.lastIndexOf(4));    //5
alert(numbers.indexOf(4, 4));     //5
alert(numbers.lastIndexOf(4, 4)); //3       
var person = { name: "Nicholas" };
var people = [{ name: "Nicholas" }];
var morePeople = [person];
alert(people.indexOf(person));     //-1
alert(morePeople.indexOf(person)); //0

##迭代方法:對數組中的每一項運行給定的函數
#every()和some()
//every():如果給定函數對每一項都返回true,則返回true
//some():如果給定函數對任意一項返回true,則返回true
var numbers = [1,2,3,4,5,4,3,2,1];

var everyResult = numbers.every(function(item, index, array){
    return (item > 2);
});
alert(everyResult);       //false

var someResult = numbers.some(function(item, index, array){
    return (item > 2);
});
alert(someResult);       //true

#filter()
//返回給定函數會返回true的項組成的數組
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]

#map()
//返回每次給定函數調用的結果組成的數組
var numbers = [1,2,3,4,5,4,3,2,1];
var mapResult = numbers.map(function(item, index, array){
    return item * 2;
});
alert(mapResult);   //[2,4,6,8,10,8,6,4,2]

#forEach()
//沒有返回值
var numbers = [1,2,3,4,5,4,3,2,1];
numbers.forEach(function(item,index,array){
    //執行某些操作
});
##

#reduce()和reduceRight()
//reduce從第一項開始,reduceRight從最後一項
var values = [1,2,3,4,5];
var sum = values.reduce(function(prev, cur, index, array){
    return prev + cur;
});
alert(sum);

##Number類型
var numberObject = new Number(10);
var numberValue = 99;

#toString() using a radix
alert(numberObject.toString());       //"10"
alert(numberObject.toString(2));      //"1010"
alert(numberObject.toString(8));      //"12"
alert(numberObject.toString(10));     //"10"
alert(numberObject.toString(16));     //"a"

#toFixed()
alert(numberObject.toFixed(2));    //outputs "10.00"

#toPrecision()
numberObject = new Number(99);
alert(numberObject.toPrecision(1));    //"1e+2"
alert(numberObject.toPrecision(2));    //"99"
alert(numberObject.toPrecision(3));    //"99.0"

alert(typeof numberObject);   //object
alert(typeof numberValue);    //number
alert(numberObject instanceof Number);  //true
alert(numberValue instanceof Number);   //false
##
  • 字符串類型
#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"

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));     //"" (empty string)

#indexOf()和lastIndexOf()
var stringValue = "hello world";
alert(stringValue.indexOf("o"));         //4
alert(stringValue.lastIndexOf("o"));     //7
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"

#trim()
var str="    Hello World     ";
var trimmedStr=str.trim();
alert(str);//"    Hello World     "
alert(trimmedStr);//"Hello World"

#字符串大小寫轉換
var stringValue = "hello world";
alert(stringValue.toLocaleUpperCase());  //"HELLO WORLD"
alert(stringValue.toUpperCase());        //"HELLO WORLD"
alert(stringValue.toLocaleLowerCase());  //"hello world"
alert(stringValue.toLowerCase());        //"hello world"

#字符串的模式匹配
var text = "cat, bat, sat, fat"; 
var pattern = /.at/;

var matches = text.match(pattern);        
alert(matches.index);        //0
alert(matches[0]);           //"cat"
alert(pattern.lastIndex);    //0

var pos = text.search(/at/);
alert(pos);   //1

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

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

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\">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(/[^\,]+/); //["", ",", ",", ",", ""]

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

//preferred technique for using 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");
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章