以下藍(lán)色字并無鏈接,只為醒目,只為醒目,只為醒目!更多示例<----只有這個是真鏈接
ECMAScript中的數(shù)組的每一項可以保存任何類型的數(shù)據(jù),數(shù)組大小可隨著數(shù)據(jù)的添加自動增長以容納新增數(shù)據(jù)。
創(chuàng)建數(shù)組
創(chuàng)建數(shù)組之——Array構(gòu)造函數(shù)
var colors = new Array(); //創(chuàng)建一個數(shù)組
var colors = new Array(20); //創(chuàng)建一個length值為20的數(shù)組
var colors = new Array("red","blue"); //創(chuàng)建一個包括兩個字符串值的數(shù)組
var colors = Array(3); //使用Array構(gòu)造函數(shù)時可省略new操作符,創(chuàng)建一個包含3項的數(shù)組
var colors = Array("green"); //創(chuàng)建一個包含一項,即字符串"green"的數(shù)組
創(chuàng)建數(shù)組之——數(shù)組字面量
var colors = ["red","blue","green"]; //創(chuàng)建一個包含三個字符串的數(shù)組
var names = []; //創(chuàng)建一個空數(shù)組
編輯數(shù)組
讀取和設(shè)置數(shù)組的值時,要使用方括號并提供項目索引。
var colors = ['red', 'blue', 'green']; //定義一個字符串?dāng)?shù)組
console.log(colors[0]); //打印第一項 red
colors[2] = 'black'; //修改第三項
colors[3] = 'brown'; //新增第四項
console.log(colors.length); //打印數(shù)組的長度 4
colors.length = 2 //將數(shù)組長度改為2
console.log(colors[2]); //打印數(shù)組索引為2的項 undefined
colors.length = 4; //將數(shù)組長度改為4
console.log(colors[2]); //打印數(shù)組索引為2的項 undefined
console.log(colors[3]); //打印數(shù)組索引為3的項 undefined
colors[colors.length] = 'pink'; //在數(shù)組末尾添加新項
colors[colors.length] = 'yellow'; // 在數(shù)組末尾添加新項
console.log(colors); //打印數(shù)組 ['red','blue',undefined,undefined,'pink','yellow']
colors[99] = 'white'; //在位置99添加一項
console.log(colors.length); //打印數(shù)組長度 100
檢測數(shù)組
- 只有一個全局執(zhí)行環(huán)境
if (value instanceof Array) {
//對數(shù)組執(zhí)行某些操作
}
- 不區(qū)分在哪個全局執(zhí)行環(huán)境,只判斷是不是數(shù)組
if (Array.isArray(value)) {
//對數(shù)組執(zhí)行某些操作
}
示例:
var colors = ['red', 'blue', 'green'];
Array.isArray(colors); //true
- 還有另外一個不是很常用的
[].constructor===Array;//true
- 適用于所有類型檢測方法
var arr=new Array();
Object.prototype.toString.call(arr);//"[object Array]"
Object.prototype.toString.call()適用于所有類型,有代碼如下:
var type = function (o){
var s = Object.prototype.toString.call(o);
return s.match(/\[object (.*?)\]/)[1].toLowerCase();
};
type({}); // "object"
type([]); // "array"
type(5); // "number"
type(null); // "null"
type(); // "undefined"
type(/abcd/); // "regex"
type(new Date()); // "date
方法
方法就是函數(shù),函數(shù)主要看三個點:函數(shù)名、參數(shù)、返回值,統(tǒng)稱為函數(shù)簽名。
轉(zhuǎn)換方法
所有對象都具有toLocalString(),toString(),valueOf()方法。
- 調(diào)用數(shù)組的toString()方法返回數(shù)組中每個值的字符串形式拼接而成的以逗號分隔的字符串,實際上為創(chuàng)建這個字符串會調(diào)用數(shù)組的每一項的toString()方法;
- 調(diào)用valueOf()方法返回的還是數(shù)組;
- 調(diào)用toLocaleString()方法返回數(shù)組中每個值的字符串形式拼接而成的以逗號分隔的字符串,實際上為創(chuàng)建這個字符串會調(diào)用數(shù)組的每一項的toLocaleString()方法,很多情況下toString()和toLocaleString()得到的結(jié)果相同;
var colors = ['red','blue','green'];
console.log(colors.toString()); //red,blue,green
console.log(colors.toLocaleString()); //red,blue,green
console.log(colors.valueOf()); //["red", "blue", "green"]
console.log(colors); //["red", "blue", "green"]
如果把console.log替換為alert,以上4個得到的結(jié)果相同。
再看一個證明toString()方法與toLocaleString()方法不同的例子:
var str1 = {
toString: function () {
return "dot";
},
toLocaleString: function () {
return "dolby";
}
};
var str2 = {
toString: function () {
return 2;
},
toLocaleString: function () {
return 3;
}
};
var str = [str1, str2];
console.log(str); //[{...},{...}]
console.log(str.toString()); //dot,2
console.log(str.toLocaleString()); //dolby,3
數(shù)組繼承的toLocalString(),toString(),valueOf()方法默認(rèn)情況下都以逗號分隔字符串的形式返回數(shù)組項,join()方法可改變這一點。
join()方法接受一個參數(shù),即用作分隔符的字符串,返回包含所有數(shù)組項的字符串,不過不給join()方法傳入?yún)?shù)或者傳入undefined,則使用默認(rèn)的逗號作為分隔符。
如果數(shù)組中的某一項值為null或undefined,該值在join(),toLocalString(),toString(),valueOf()方法返回的結(jié)果中以空字符串表示。
var colors = ['red', 'blue', null, 'green', undefined];
console.log(colors.join('||')); //red||blue||||green||
console.log(colors.join('-')); //red-blue--green-
另:join()經(jīng)常與字符串的split()方法一起使用。split()根據(jù)傳入的字符將字符串分割為數(shù)組,返回生成的數(shù)組,join將數(shù)組拼接成字符串。
var str = '1-2-3-4-5';
console.log(str.split('-').join('')); //12345
棧方法
棧是一種后進(jìn)先出的數(shù)據(jù)結(jié)構(gòu)(可想象為死胡同)。適當(dāng)?shù)姆椒ㄗ寯?shù)組可以表現(xiàn)得像棧一樣,棧中項的推入push()和彈出pop()只發(fā)生在棧的頂部。
push()方法接收任意數(shù)量的參數(shù)并把它們按順序逐個添加到數(shù)組末尾,返回的是修改后數(shù)組的長度;pop()方法從數(shù)組末尾移除最后一項,減少數(shù)組length值,返回移除的項。
var colors = ['red', 'blue', null, 'green', undefined];
console.log(colors.push('white', 'black')); //7
colors[7] = 'pink';
console.log(colors.length); //8
var item = colors.pop();
console.log(item); //pink
console.log(colors); //["red", "blue", null, "green", undefined, "white", "black"]
隊列方法
隊列是一種先進(jìn)先出的數(shù)據(jù)結(jié)構(gòu)。有兩種操作方法。
var colors = Array();
var count = colors.push('red', 'pink');
console.log(count); //2
count = colors.push('white');
var item = colors.shift();
console.log(item); //red
console.log(colors); //["pink","white"]
var count1 = colors.unshift('blue', 'yellow');
console.log(count1); //4
var item1 = colors.pop();
console.log(item1); //white
console.log(colors); //["blue", "yellow", "pink"]
重排序方法
- reverse()反轉(zhuǎn)數(shù)組項順序——簡單粗暴,適用于僅需要反轉(zhuǎn)的場景
- sort()比較后重排序——調(diào)用每個數(shù)組項的toString()方法后比較得到的字符串,默認(rèn)將比較后的值從小到大排列,這種默認(rèn)方法不是最佳方案,所以sort()方法需要接收一個比較函數(shù)作為參數(shù)以便我們指定排序規(guī)則。
reverse()和sort()方法的返回值是經(jīng)過重排序之后的數(shù)組,即原數(shù)組發(fā)生了改變。
// 定義一個數(shù)組并反轉(zhuǎn)數(shù)組項,原數(shù)組發(fā)生了改變
var values = [3, 8, -6, 1, 9];
values.reverse(); //反轉(zhuǎn)數(shù)組項
console.log(values); //[9, 1, -6, 8, 3]
// 對于數(shù)值類型或者valueOf()返回數(shù)值類型的對象類型,做比較可以更簡單
// 定義一個compare函數(shù),
function compare1(value1, value2) {
return value2 - value1; //做減法,比較的第二項大于第一項則排在前面,即降序排列,value1-value2即升序排列
}
values.sort(compare1); //將compare函數(shù)當(dāng)作參數(shù)傳遞給sort()方法
console.log(values); //[9, 8, 3, 1, -6]
// 以下兩個排序方法適用于大多數(shù)數(shù)據(jù)類型
// 升序排列
function compare2(value1, value2) {
if(value1<value2) {
return -1;
}else if(value1>value2){
return 1;
}else{
return 0;
}
}
values.sort(compare2);
console.log(values); //[-6, 1, 3, 8, 9]
// 降序排列
function compare3(value1, value2) {
if(value1<value2) {
return 1;
}else if(value1>value2){
return -1;
}else{
return 0;
}
}
values.sort(compare3);
console.log(values); // [9, 8, 3, 1, -6]
操作方法
- concat()會創(chuàng)建當(dāng)前數(shù)組的一個副本,然后將接收到的參數(shù)的每一項作為新增項添加到這個副本末尾,返回新構(gòu)建的數(shù)組,沒有給concat()方法傳入?yún)?shù)的情況下它只會復(fù)制當(dāng)前數(shù)組并返回副本。
- slice()基于當(dāng)前數(shù)組中的若干個項創(chuàng)建一個新數(shù)組,接受一到兩個參數(shù),即返回項的起始位置和結(jié)束位置(不包括結(jié)束位置)的項,只有一個參數(shù)的情況下返回該參數(shù)指定位置開始到當(dāng)前數(shù)組末尾的所有項。
concat()和slice()方法的返回新數(shù)組,即原數(shù)組不會被改變。
var colors = ['red', 'green', 'blue', 'pink'];
var colors1 = colors.concat();
var colors2 = colors.concat('yellow', ['black', 'brown']);
var color3 = colors.slice(1);
var color4 = colors.slice(2, 3);
console.log(colors1); //["red", "green", "blue", "pink"]
console.log(colors2); //["red", "green", "blue", "pink", "yellow", "black", "brown"]
console.log(color3); //["green", "blue", "pink"]
console.log(color4); //["blue"]
console.log(colors); //["red", "green", "blue", "pink"]
-
splice()方法
splice()方法主要用途為向數(shù)組中插入項,該方法始終都會返回一個數(shù)組,該數(shù)組中包含從原始數(shù)組中刪除的項(如果沒有刪除任何項則返回一個空數(shù)組),此方法會改變原始數(shù)組。
以下是用法:- 刪除:可刪除任意數(shù)量的項,2個參數(shù),要刪除的第一項的位置(包括第一項)和要刪除的項數(shù)。
- 插入:可向指定位置插入任意數(shù)量的項,最少3個參數(shù),起始位置(在起始位置之前插入)、0(刪除0項)、要插入的那一項,如要插入多個項,可再傳入第4、第5以至任意多個項。
- 替換:可向指定位置插入任意數(shù)量的項同時刪除任意數(shù)量的項,最少3個參數(shù),起始位置(從起始位置開始計算)、要刪除的項數(shù)、要插入的那一項,如要插入多個項,可再傳入第4、第5以至任意多個項,插入項數(shù)與刪除項數(shù)不必一致。
var colors = ['red', 'green', 'blue', 'pink'];
var removed = colors.splice(0, 1);
console.log(removed); //["red"]
console.log(colors); //["green", "blue", "pink"]
removed = colors.splice(1, 0, 'yellow', 'white', 'white')
console.log(removed); //[]
console.log(colors); //["green", "yellow", "white", "white", "blue", "pink"]
removed = colors.splice(2, 1, 'yellowgreen');
console.log(removed); //["white"]
console.log(colors); //["green", "yellow", "yellowgreen", "white", "blue", "pink"]
位置方法
- indexOf():從數(shù)組的位置0開始向后查找
- lastIndexOf():從數(shù)組的末尾開始向前查找
這兩個方法都接收兩個參數(shù),要查找的項和(可選的)表示查找起點位置(包括起點位置)的索引。都返回要查找的項在數(shù)組中的位置,在沒找到的情況下返回-1。比較第一個參數(shù)與數(shù)組中的每一項時要求全等,必須嚴(yán)格相等!
var values = [1, 2, 3, 4, 5, 4, 3, 2, 1];
console.log(values.indexOf(4)); //3
console.log(values.indexOf(4, 5)); //5,從索引5開始向右查找4,找到了索引5的值就是4,返回索引5
console.log(values.lastIndexOf(3)); //6
console.log(values.lastIndexOf(5, 1)); //-1,從索引1開始向左查找5,沒找到,返回-1
迭代方法
ECMAScript5位數(shù)組定義了5個迭代方法,每個方法都接收兩個參數(shù):要在每一項上運行的函數(shù)和(可選的)運行該函數(shù)的作用域?qū)ο蟆绊憈his的值。
而第一個參數(shù),也就是回調(diào)函數(shù),接收三個參數(shù):數(shù)組項的值,該項在數(shù)組中的位置和數(shù)組對象本身,一般可忽略第三個參數(shù)。
根據(jù)使用方法的不同,這個函數(shù)執(zhí)行后的返回值可能會影響方法的返回值。
以下方法都不會影響原數(shù)組。
- every():對數(shù)組的每一項運行給定函數(shù),如果該函數(shù)對每一項都返回true則返回true
- some():對數(shù)組中的每一項運行給定函數(shù),如果該函數(shù)對任意一項返回true則返回true
- filter():對數(shù)組的每一項運行給定函數(shù),返回該函會返回true的項組成的新數(shù)組
- map():對數(shù)組中的每一項運行給定函數(shù),返回每次函數(shù)調(diào)用的結(jié)果組成的數(shù)組
- forEach():對數(shù)組中的每一項運行給定函數(shù),這個方法沒有返回值
every()和some()就像邏輯與和邏輯非,用于查詢數(shù)組中的項是否滿足某個條件。
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var everyResult = numbers.every(function (item, index, arr) {
return item > 2;
}, numbers);
console.log(everyResult); //false
var someResult = numbers.some(function (item, index, arr) {
return item > 2;
}, numbers);
console.log(someResult); //true
filter()過濾器,利用指定函數(shù)過濾出需要的項,適合查詢符合某些條件的所有數(shù)組項。
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var filterResult = numbers.filter(function (item, index, arr) {
return item > 2;
}, numbers)
console.log(filterResult); //[3, 4, 5, 4, 3]
map()中的每一項都是在原始數(shù)組中對應(yīng)項上運行傳入函數(shù)的結(jié)果,此方法適合創(chuàng)建包含的項與另一數(shù)組一一對應(yīng)的數(shù)組。
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var mapResult = numbers.map(function (item, index, arr) {
return item * 2;
}, numbers)
console.log(mapResult); //[2, 4, 6, 8, 10, 8, 6, 4, 2]
forEach():對數(shù)組中的每一項運行給定函數(shù),這個方法沒有返回值,本質(zhì)上與使用for循環(huán)迭代數(shù)組一樣。
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var forEachResult = numbers.forEach(function (item, index, arr) {
return item * item;
});
console.log(forEachResult); //undefined
因為沒有返回值,所以打印undefined。
歸并方法
以下兩個方法都會迭代數(shù)組的所有項然后構(gòu)建一個最終返回的值,都接收兩個參數(shù):一個在每一項上調(diào)用的函數(shù)和(可選的)作為歸并基礎(chǔ)的初始值。
- reduce():從數(shù)組第一項開始逐個遍歷到最后。
- reduceRight():從數(shù)組最后一項開始向前遍歷到第一項。
作為第一個參數(shù)的函數(shù)接收四個參數(shù):前一個值、當(dāng)前值、項的索引、數(shù)組對象。這個函數(shù)返回的任何值都會作為第一個參數(shù)自動傳給下一項。
第一次迭代發(fā)生在數(shù)組的第二項上,因此第一個參數(shù)是數(shù)組的第一項,第二個參數(shù)是數(shù)組的第二項。
使用reduce()可以求數(shù)組中所有值之和。
var numbers = [1, 2, 3, 4, 5, 4, 3, 2, 1];
var sum = numbers.reduce(function (prev, cur, index, array) {
return prev + cur;
});
console.log(sum); //25
reduceRight()與reduce()只是方向相反。
var numbers = [1, 2, 3, 4, 5, 6, 7];
var sum = numbers.reduceRight(function (prev, cur, index, array) {
return prev - cur;
});
console.log(sum); //-14