1. 程式人生 > >【js實例】Array類型的9個數組方法,Date類型的41個日期方法,Function類型

【js實例】Array類型的9個數組方法,Date類型的41個日期方法,Function類型

win .html number 火狐瀏覽器 nds 位數 天數 start 基本數據類型

前文提要:【js實例】js中的5種基本數據類型和9種操作符

Array類型的9個數組方法

Array中有9個數組方法:

1.檢測數組 2.轉換方法 3.棧方法 4.隊列方法 5.沖排序方法
6.操作方法 7.位置方法 8.叠代方法 9.歸並方法

在實例中介紹,實例如下

/*
Array類型
js數組中的每一項可以用來保存任何類型的數據;js數組的大小是可以動態調整的
*/
var colors = ["red", "blue", "green"];
alert(colors[0]);    //red
alert(colors[1]);    //blue
alert(colors[2]);    //
green alert(colors[3]); //undefined alert(colors.length); /*
1.
檢測數組:
instanceof(), isArray()
*/
if (colors instanceof Array) { alert("yes"); //yes } if (Array.isArray(colors)) { alert("yes"); //yes } /* 轉換方法:
toString(), toLocaleString(), valueOf() alert()要接收字符串參數,當傳入alert()的不是字符串參數時它會在後臺調用toString()方法
*/ //返回一個字符串,字符串由數組中每個值的字符串組成,並且以逗號分隔 alert(colors.toString()); //通常和toString()方法一樣,但是它是調用數組中每一項的toLocaleString()方法 alert(colors.toLocaleString()); //先是valueOf()方法,調用toString()方法,(valueOf返回的是數組) alert(colors.valueOf()); alert(colors); //join接收一個參數,返回以參數做分隔符的所有數組項的字符串 alert(colors.join("~")); //
red~blue~green /* 棧方法:push()和pop() push()向數組中添加元素,返回修改後數組的長度 pop()移除數組中最後一項,返回移除的項 */ var colors = ["red", "blue", "green"]; var count = colors.push("white", "yellow"); alert(count); //5 alert(colors.length); //5 alert(colors); //red,blue,green,white,yellow var item = colors.pop(); alert(item); //yellow alert(colors.length); //4 alert(colors); //red,blue,green,white /* 隊列方法:shift()和unshift() shift()移除數組的第一項並返回移除的項 unshift()在數組的第一項之前添加任意項,並返回數組的長度 */ var colors = ["red", "blue", "green"]; var item = colors.shift(); //shift() alert(item); //red alert(colors.length); //2 alert(colors); //blue,green //unshift() var count = colors.unshift("white", "yellow"); alert(count); //4 alert(colors.length); //4 alert(colors); //white,yellow,blue,green /* 排序方法:reverse()和sort() reverse()會反轉數組想的順序,返回排序後的數組 sort()比較的是字符串,接收的參數會調用每個數組項的toString()方法,返回排序後的數組 sort()接收的參數也可以是函數 */ //reverse() var value = [1, 3, 5, 2, 10]; var values = value.reverse(); alert(value); //10,2,5,3,1 alert(values); //10,2,5,3,1 //sort() var value = [1, 3, 5, 2, 10]; var values = value.sort(); alert(value); //1,10,2,3,5 alert(values); //1,10,2,3,5 /* 操作方法:concat(), slice()和splice() concat()創建當前數組的副本,若有參數則將其添加到副本數組尾部,最後返回新創建的數組 slice()基於當前數組創建新數組,但是不改變原數組;接收兩個參數start, end start為返回項的起始位置,end為返回項的結束位置(具體見例子), splice(),接收2個或3個參數通常用於刪除,插入或替換(插入和替換都要產生刪除操作,刪除項數可為0),返回刪除的項 刪除:splice(x, y); x為刪除的起始位置,y為要刪除的項數 插入和替換(通過改變參數實現):splice(x, y, z); x為起始位置,y為要刪除的項數,z為要插入的項;z可以是任意多個項 */ //concat() var colors = ["red", "blue", "green"]; var colors2 = colors.concat(); alert(colors); //red,blue,green alert(colors2); //red,blue,green var colors3 = colors.concat("yellow", ["black", "brown"]); alert(colors); //red,blue,green alert(colors3); //red,blue,green,yellow,black,brown //slice() var colors = ["red", "blue", "green", "yellow", "black"]; //1.若有一個參數,則返回從起始位置到原數組末尾所組成的數組 var colors2 = colors.slice(1); //2.若有兩個參數,則返回從起始位置到結束位置前一項所組成的數組 var colors3 = colors.slice(1, 4); //3.若start < end時返回空數組 var colors4 = colors.slice(2, 1); //4.若參數為負數,則參數加上數組長度作為start或者end var colors5 = colors.slice(-3, -1); alert(colors); //red,blue,green,yellow,black alert(colors2); //blue,green,yellow,black alert(colors3); //blue,green,yellow alert(colors4); //返回空數組,屏幕上顯示空白警告框 alert(colors5); //green,yellow //splice() //刪除 var colors = ["red", "blue", "green", "yellow", "black"]; var remove = colors.splice(1, 2); alert(colors); //red,yellow,black alert(remove); //blue,green //插入 var colors = ["red", "blue", "green", "yellow", "black"]; var remove2 = colors.splice(1, 0, "white", "brown"); //刪除項數為0 alert(colors); //red,white,brown,blue,green,yellow,black alert(remove2); //空數組 //替換 var colors = ["red", "blue", "green", "yellow", "black"]; var remove2 = colors.splice(1, 1, "white", "brown"); //刪除項數為1 alert(colors); //red,white,brown,green,yellow,black alert(remove2); //blue /* 位置方法:indexOf()和lastIndexOf() 兩個方法用於返回查找項在數組中的位置,未找到返回-1;都接收兩個參數x和y, x:要查找的項;y:查找起始點位置的索引(可選參數) indexOf()從數組開頭向後查找查找並返回查找參數的第一個位置,找不到返回-1; lastIndexOf()從數組末尾向前查找,返回查找參數的第一個位置 註意:要查找的項必須嚴格相等(===) */ var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; //indexOf() alert(numbers.indexOf(4)); //3 alert(numbers.indexOf(4, 4)); //5 alert(numbers.indexOf(4, 6)) //-1 alert(numbers.indexOf(10)); //-1 //lastIndexOf() alert(numbers.lastIndexOf(4)); //5 alert(numbers.lastIndexOf(4, 4)); //3 alert(numbers.lastIndexOf(4, 2)); //-1 alert(numbers.lastIndexOf(10)) //-1 //要查找的項必須嚴格相等(===) var person = {name : "Nicholas"}; var people = [{name : "Nicholas"}]; var morePeople = [person]; //註意這是數組 alert(people.indexOf(person)); //-1 alert(morePeople.indexOf(person)); //0 /* 叠代方法:every(), filter(), forEach(), map(), some() 每個方法接收兩個參數:函數參數x,運行該函數的作用域對象y 函數參數x接收三個參數:數組項的值,該項在數組中的位置和數組對象本身 every():對數組中的每一項運行給定的函數,如果該函數對每一項都返回true,則返回true some():對數組中的每一項運行給定的函數,如果該函數中某一項返回true,則返回true filter():對數組中的每一項運行給定的函數,返回該函數會返回true的項組成的數組 forEach():對數組中的每一項運行給定的函數,無返回值 map():對數組中的每一項運行給定的函數,返回每次函數調用結果組成的數組 */ var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1]; //every() var everyResult = numbers.every(function(item, index, array) { return (item > 2); }); alert(everyResult); //false //some() var someResult = numbers.some(function(item, index, array) { return (item > 2); }); alert(someResult); //true //filter() var filterResult = numbers.filter(function(item, index, array) { return (item > 2); }); alert(filterResult); //3,4,5,4,3 //map() var mapResult = numbers.map(function(item, index, array) { return item * 2; }); alert(mapResult); //2,4,6,8,10,8,6,4,2 /* 歸並方法:reduce()和reduceRight() 接收兩個參數:一個在數組每一項調用的函數x,作為歸並基礎的初始值y(可選) 函數x:接收四個參數,前一個值,當前值,項的索引和數組對象 reduce():從數組的第一項開始 reduceRight():從數組的最後一項開始 */ var values = [1, 2, 3, 4, 5]; //reduce() var sum = values.reduce(function(prev, cur, index, array) { return prev + cur; }); alert(sum); //"15" //redeceRight() var sum2 = values.reduceRight(function(prev, cur, index, array) { return prev + cur; }) alert(sum2); //"15"

Date類型的41個日期方法

Date類型可分為如下:

繼承的方法:Date(), parse(),toLocaleString(),toString()和valueOf()方法;

日期格式化方法:

toDateString()
toTimeString()
toLocaleDateString()
toLocaleTimeString()
toUTCString()

日期/時間組件方法:getTime(), getTimezoneOffset()等

具體在實例中給出:

/*
Date類型
*/
var now = new Date();
alert(now);
//繼承的方法
//Date.parse()接收一個表示日期的字符串參數,根據參數返回相依日期的毫秒數;
//ECMA-262規範沒有定義此函數支持的格式,應地區實現而異
var someDate = new Date(Date.parse("May 25, 2004"));    
alert(someDate);    //Tue May 25 2004 00:00:00 GMT+0800

//Date.UTC()方法接收7個參數:年year,月month(0開始),日day(1-31),小時hour(0-23),分鐘min,秒s,毫秒ms
//year和month為必須參數;day默認為1,其它參數默認為0

var y2k = new Date(Date.UTC(2000, 0));    
alert(y2k);            //Sat Jan 01 2000 08:00:00 GMT+0800

var allFives = new Date(Date.UTC(2005, 4, 5, 17, 55, 55, 3600));
alert(allFives);    //Fri May 06 2005 01:55:58 GMT+0800

//Date()構造函數會模仿Date.parse()和Date.UTC()方法
var d = new Date("May 25, 2004");
var dd = new Date(2005, 4, 5, 17, 55, 55, 3600);
alert(d);        //Tue May 25 2004 00:00:00 GMT+0800
alert(dd);        //Fri May 06 2005 01:55:58 GMT+0800


/*
Date類型也重寫了toLocaleString(),toString()和valueOf()方法;
但是瀏覽器之間對toLocaleString()和toString()輸出不一致.下面輸出為火狐瀏覽器下輸出
*/
var date = new Date("1, 1, 2001");
alert(date);                    //Mon Jan 01 2001 00:00:00 GMT+0800
alert(date.toLocaleString());    //2001/1/1 上午12:00:00
alert(date.toString());            //Mon Jan 01 2001 00:00:00 GMT+0800
//註意:valueOf()方法返回的是日期的毫秒數
alert(date.valueOf());            //978278400000


/*
日期格式化的方法
這些方法也是因瀏覽器而異,以下為火狐瀏覽器輸出
*/
var date = new Date("1, 1, 2001");
//toDateString():以特定於實現的格式顯示星期幾,月,日和年
alert(date.toDateString());        //Mon Jan 01 2001
//toTimeString():以特定於實現的格式顯示時,分,秒和時區
alert(date.toTimeString());        //00:00:00 GMT+0800
//toLocaleDateString():以特定於地區的格式顯示星期幾,月,日和年
alert(date.toLocaleDateString());        //2001/1/1
//toLocaleTimeString():以特定於實現的格式顯示時,分,秒
alert(date.toLocaleTimeString());        //上午12:00:00
//toUTCString():以特定與實現的格式完整的UTC日期
alert(date.toUTCString());        //Sun, 31 Dec 2000 16:00:00 GMT


/*
日期/時間組件方法
*/
var date = new Date(2001, 1, 1);
//返回表示日期的毫秒數,與valueOf()返回的值相同
alert(date.getTime());
//返回本地時間與UTC世紀那相差的分鐘數
alert(date.getTimezoneOffset());
//以毫秒數設置日期,傳入參數為毫秒
alert(date.setTime(3600000000000));//參數為為毫秒數

//
var date = new Date(2001, 1, 1);
//取得四位數的年份
alert(date.getFullYear());
//返回UTC日期的4位數年份
alert(date.getUTCFullYear());
//設置日期年份,傳入參數必須為4位數
alert(date.setFullYear(2002));    //參數為年
//設置UTC日期年份,傳入參數必須為4位數
alert(date.setUTCFullYear(2003));//參數為年

//月:0-11
var date = new Date(2001, 1, 1);
//返回日期中的月份
alert(date.getMonth());
//返回UTC日期中的月份
alert(date.getUTCMonth());
//設置日期的月份,傳入參數必須大於0,超過則增加年份
alert(date.setMonth(1));//參數為月
//設置UTC日期的月份,傳入參數必須大於0,超過則增加年份
alert(date.setUTCMonth(2));//參數為月

//日:1-31
var date = new Date(2001, 1, 1);
//返回日期月份中的天數
alert(date.getDate());
//返回UTC日期月份中的天數
alert(date.getUTCDate());
//設置日期月份中的天數
alert(date.setDate(23));//參數為日
//設置UTC日期月份中的天數
alert(date.setUTCDate(24));//參數為日

//星期:1-6,0表示星期日
var date = new Date(2001, 1, 1);
//返回日期中的星期幾
alert(date.getDay(2));
//返回UTC日期中的星期幾
alert(date.getUTCDay(3));

//時:0-23
var date = new Date(2001, 1, 1);
//返回日期中的小時數
alert(date.getHours());
//返回UTC日期中的小時數
alert(date.getUTCHours());
//設置日期中的小時數
alert(date.setHours(2));//參數為時
//設置UTC日期中的小時數
alert(date.setUTCHours(3));//參數為時


//分:0-59
var date = new Date(2001, 1, 1);
//返回日期中的分鐘數
alert(date.getMinutes());
//返回UTC日期中的分鐘數
alert(date.getUTCMinutes());
//設置日期中的分鐘數
alert(date.setMinutes(34));//參數為分
//設置UTC日期中的分鐘數
alert(date.setUTCMinutes(35));//參數為分


//秒:0-59
var date = new Date(2001, 1, 1);
//返回日期中的秒數
alert(date.getSeconds());
//返回UTC日期中的秒數
alert(date.getUTCSeconds());
//設置日期中的秒數
alert(date.setSeconds(45));//參數為秒
//設置UTC日期中的秒數
alert(date.setUTCSeconds(46));//參數為秒

//毫秒
var date = new Date(2001, 1, 1);
//返回日期中的毫秒數
alert(date.getMilliseconds());
//返回UTC日期中的毫秒數
alert(date.getUTCMilliseconds());
//設置日期中的毫秒數
alert(date.setMillseconds(3454));//參數為毫秒
//設置UTC日期中的毫秒數
alert(date.setUTCMillseconds(1111));//參數為毫秒

Function類型

/*
函數Function 類型
*/
/*
1.函數是對象,函數名是只想函數對象的指針,不會與函數綁定(函數是對象,函數名是指針)
*/
function sum(num1, num2) {
    return num1 + num2;
}
alert(sum(10, 10));    //20

var anotherSum = sum;
alert(anotherSum(10, 10));    //20

//sum是函數的指針並不與函數綁定
sum = null;
alert(anotherSum(10, 10));    //20

/*
2.函數沒有重載
*/
function addNum(num) {
    return num + 100;
}

function addNum(num) {
    return num + 200;
}

alert(addNum(100));    //300


/*
3.解析器會通過“函數聲明提升”將函數聲明添加到執行環境中去,而函數表達式則須解析器執行到它所在的代碼行才會被執行
*/
alert(sum(10, 10));    //20
function sum(num1, num2) {
    return num1 + num2;
}

alert(sum2(19, 10));    //error
var sum2 = function(num1, num2) {
    return num1 + num2;
}

/*
4.函數的內部屬性:arguments和this,callee,caller
註意:不能在嚴格模式下使用callee,caller
*/
//arguments保存函數的參數,該對象還有一個callee的屬性,callee是一個指針,指向擁有arguments對象的函數
function factorial(num) {
    if (num <= 1) {
        return -1;
    } else {
        return num * arguments.callee(num - 1);
    }
}

alert(4);        //24


//this引用的是函數執行的環境對象。
var color = "red";
var o = {color : "blue"};

function showColor() {
    alert(this.color);
}

//直接調用函數則this引用的環境對象是window
showColor();        //red
alert(window.color);//red
//this引用的環境對象是o,所以調用的是o中的color
o.showColor();        //red


/*
caller保存至調用當前函數的函數的引用(在全局作用域中調用當前函數則值為null),除opera早期版本不支持外其他都支持,
註意:ECMAScript並沒有定義這個屬性
*/
function outer() {
    inner();
}

function inner() {
    alert(inner.caller);
}

outer();    //顯示outer函數的源代碼


/*
apply(), call()
apply():接收兩個參數x,y;x為運行函數的作用域,y為參數數組(可以為Array實例)
call():第一個參數與apply()類似,但是後面的參數不已數組形式傳遞,而是直接傳遞給數組
*/
function sum(num1, num2) {
    return num1 + num2;
}

//註意:在嚴格模式下,未指定環境對象而調用函數則this值不會轉型為window,this此時為undefined
function callSum1(num1, num2) {
    return sum.apply(this, arguments);
}
function callSum2(num1, num2) {
    return sum.apply(this, [num1, num2]);
}
alert(callsum1(10 ,10));    //20
alert(callsum2(10 ,10));    //20


function sum(num1, num2) {
    return num1 + num2;
}
function callSum(num1, num2) {
    return sum.call(this, num1, num2);
}
alert(callSum(10, 10));        //20

【js實例】Array類型的9個數組方法,Date類型的41個日期方法,Function類型