標籤:
稀疏數組
var a1 = [, , , ];var a2 = new Array(3);var a3 = [1, 2, 3];console.log(0 in a1);//falseconsole.log(0 in a2);//falseconsole.log(0 in a3);//truedelete a3[0];console.log(0 in a3);//false
數組元素的增減
length設定小於原值,刪除溢出的;新增一數組元素,length始終元素序號+1。
push/pop在數組尾部操作,與a[a.length]賦值一樣;可支援多參數。
unshift/shift在數組頭部操作
數組遍曆
if (!a(i))//null/undefined/不存在的元素if (a(i) === undefined)if (!(i in a))//不存在的元素
可用for in處理稀疏數組,不過數組不推薦用這個,比如能夠枚舉繼承的屬性名稱。
數組的校正和類數組
Array.isArray = Array.isArray || function (o) { return typeof o === "object" && Object.prototype.toString.call(o) === "[object Array]";}
類數組對象:可用針對真正數組遍曆的代碼來遍曆;可用數組的通用方法。
function isArrayLike(o) { if (o && typeof o === ‘object‘ && o.nodeType != 3 && isFinite(o.length) && o.length >= 0 && o.length === Math.floor(o.length) && o.length < 4294967296) return true; else return false;}作為數組的字串
在ES5(包括IE8)中,字串行為類似唯讀數組。除了用charAt訪問單個的字元外,還可以使用方括弧。數組的通用方法可以用到字串上。例如:
s = "JavaScript"Array.prototype.join.call(s, " ") // => "J a v a S c r i p t"Array.prototype.filter.call(s, // 過濾字串中的字元 function (x) { return x.match(/[^aeiou]/); // 只匹配非母音字母 }).join(""); // => "JvScrpt"
注意,字串是唯讀,如果使用修改調用數組的方法,會報錯。譬如:push()、sort()、reverse()、splice()等數組方法。
ES3中數組支援的方法
concat()—結果返回、sort() 、reverse() 、join()—結果返回、slice()—結果返回、splice()、push()、pop()、unshift()、shift()、toString()、toLocaleString()
concat:返回一個新建立的數組,元素包含調用concat的原始數組的元素和concat的每個參數,如果這些參數中的任何一個自身是數組,則串連的數組的元素,而非數組本身。但要注意,concat不會遞迴扁平化數組的數組,也不會修改調用的數組。
數組slice和splice方法
slice不改變原數組,截取原數組片段返回。索引從0開始,參數為正數時,第一個參數和不到第二個參數(從零算起,相對於索引)數組;參數為負數時,倒數第一個參數和倒數第二個參數的數組。
splice改變原數組。第一個參數(從零算起),插入或刪除的起始位置,第二個參數:刪除元素的個數,第三或其它任意參數,要插入的元素。
刪除數組元素,保持數組連續,就用splice,返回的由刪除元素組成的數組。複製數組的時候,請使用Array.slice。
var len = items.length, itemsCopy = [], i;// badfor (i = 0; i < len; i++) { itemsCopy[i] = items[i];}// gooditemsCopy = items.slice();ES5中數組支援的方法
forEach()、map()、filter()、every()和some()、reduce()和reduceRigth()、indexOf()和lastIndexOf()。
forEach()
var data = [1, 2, 3, 4, 5];data.forEach(function (v, i, a) { a[i] = v + 1;})
不能像for中使用break跳出迴圈,在forEach()傳入參數的函數中拋出foreach.break異常。
function foreach(a, f, t) {// a為數組,f為函數,t為函數f的執行環境 try { a.forEach(f, t); } catch (e) { if (e === foreach.break) return; else throw e; }}foreach.break = new Error("StopIteration");
在ES3不支援forEach()可引入以下方法
Array.prototype.forEach || (Array.prototype.forEach = function (fn, context) { for (var i = 0, len = this.length >>> 0; i < len; i++) { if (i in this) { fn.call(context, this[i], i, this); } }});
map()
a = [1, 2, 3];b = a.map(function (x) { return x * x;});
傳遞的參數跟forEach()一樣,不同的是map()調用的函數要有傳回值。該函數返回新建立的數組,不修改調用的數組。
Array.prototype.map = Array.prototype.map || function (callback, thisArg) { var T, A, k; if (this == null) { throw new TypeError(" this is null or not defined"); } // 1. 將O賦值為調用map方法的數組. var O = Object(this); // 2.將len賦值為數組O的長度. var len = O.length >>> 0; // 4.如果callback不是函數,則拋出TypeError異常. if ({}.toString.call(callback) != "[object Function]") { throw new TypeError(callback + " is not a function"); } // 5. 如果參數thisArg有值,則將T賦值為thisArg;否則T為undefined. if (thisArg) { T = thisArg; } // 6. 建立新數組A,長度為原數組O長度len A = new Array(len); // 7. 將k賦值為0 k = 0; // 8. 當 k < len 時,執行迴圈. while (k < len) { var kValue, mappedValue; //遍曆O,k為原數組索引 if (k in O) { //kValue為索引k對應的值. kValue = O[k]; // 執行callback,this指向T,參數有三個.分別是kValue:值,k:索引,O:原數組. mappedValue = callback.call(T, kValue, k, O); // 傳回值添加到新書組A中. A[k] = mappedValue; } // k自增1 k++; } // 9. 返回新數組A return A;};
every()和some()
對數組進行邏輯判定,返回true或false;注意every()和some()確定該返回什麼值它們就會停止遍曆數組元素。
reduce()和reduceRight()
使用指定的函數將數組元素進行組合,產生單個值。這在函數式編程中是常見的操作,稱為“注入”和“摺疊”。reduce需要兩個參數,第一個參數是執行化簡的函數,函數的參數分別為:化簡操作累計的結果或初始化值、數組元素、元素的索引、數組的本身;第二個參數(可選)是傳遞給函數的初始值。
var a = [1, 2, 3, 4, 5];var sum = a.reduce(function (x, y) { return x + y;}, 0);var product = a.reduce(function (x, y) { return x * y;}, 1);var max = a.reduce(function (x, y) { return x > y ? x : y;});
reduceRight()的工作原理和reduce()一樣,不同的是它按照數組索引從高到低(從右至左)處理數組。
indexOf()和lastIndexOf()
第一個參數代表要搜尋的元素,第二個元素代表搜尋的起始位置。可為負數,它代表相對數組末尾的位移量,-1時,指定數組的最後一個元素。
var a = [0, 1, 2, 1, 0];a.indexOf(1); // => 1:a[1]是1a.lastIndexOf(1) // => 3:a[3]是1a.indexOf(3) // =>-1: 沒有值為3的元素function findAll(a, x) { var result = [], len = a.length, pos = 0; while (pos < len) { pos = a.indexOf(x, pos); if (pos === -1) { break; } result.push(pos); pos++; }}
字串也有indexOf()和lastIndexOf()方法。
Javascript 數組總結