棧/隊列node
pop刪除最後一項(棧)
shift刪除第一項(隊列)
push增長到最後(棧)
unshift增長到最前(隊列)
reverse翻轉
join轉字符串
slice截取(切片)slice
splice剪接
concat數組合並
sort排序本質詳解es6
isArray
indexOf取索引
lastIndexOf
some經常使用
every經常使用
filter
reduce詳解
reduceRight
forEach
map
兼容低版本IE擴展的Array數組
類數組
通用類數組
特殊類數組,屬性爲0,1..含有length的{}
經常使用類數組arguments Nodelistapp
做爲數組的字符串ide
Array.from
Array.of
copyWithin
find經常使用
findIndex經常使用
fill
entries(),keys()和values()遍歷數組
includes
數組的空位wordpress
棧:桶。只有一個口(進出)。先進後出,後進先出 隊列:人隊。有兩個口。先進先出,後進後出
刪除元素的值
;若是數組爲空則返回undefinevar a = [1,2,3,4,5]; a.pop();//a:[1, 2, 3, 4] a.pop();//a:[1, 2, 3] a.pop();//a:[1, 2]
刪除元素的值
;若是數組爲空則返回undefinevar a = [1,2,3,4,5]; a.shift(); //a:[2,3,4,5] a.shift(); //a:[3, 4, 5]
新數組長度
;var a = [1,2,3,4,5]; a.push(6);//[1, 2, 3, 4, 5, 6] aa.push('xx');//[1, 2, 3, 4, 5, 6, "xx"] 返回長度7 a.push('yy');//[1, 2, 3, 4, 5, 6, "xx", "yy"] 返回長度8
新數組長度
;var a = [1,2,3,4,5]; a.unshift();//[1, 2, 3, 4, 5] a.unshift("cc");//["cc", 1, 2, 3, 4, 5] 返回長度6 a.unshift("aaa");//["aaa", "cc", 1, 2, 3, 4, 5] 返回長度7
翻轉後的原數組
,原數組翻轉了var a = [1,2,3,4,5]; a.reverse()//a:[5, 4, 3, 2, 1] 返回[5, 4, 3, 2, 1]
字符串
,原數組木變
var a = [1,2,3,4,5]; var b=a.join('||');//b:"1||2||3||4||5" a:[1,2,3,4,5]
開始索引(包含)
到結束索引(不包含)
之間的項組成的新數組
,原數組木變 ,索引從0開始var a = ['a','b','c','d','e']; a.slice(1,3);//["b", "c"] a:['a','b','c','d','e'] a.slice(0,4);//["a", "b", "c", "d"] a.slice(3,4);//["d"] /*參數爲1個*/ a.slice(2);["c", "d", "e"] //從第三個開始截取(包含),默認截到最後。索引爲數組自己長度 a.slice(0);//['a','b','c','d','e'] //新數組和老數組同樣 引用不同 值傳遞 引用傳遞 有關係 /*參數爲0個*/ a.slice();//和a.slice(0)等價 //新數組和老數組同樣 引用不同 值傳遞 引用傳遞 有關係 /*若是 slice()方法的參數中有一個負數,則用數組長度加上該數來肯定相應的位 置。例如,在一個包含 5 項的數組上調用 slice(-2,-1)與調用 slice(3,4)獲得的 結果相同。若是結束位置小於起始位置,則返回空數組。*/ a.slice(3,4);//["d"] a.slice(-2,-1);//["d"] 這種方式:是從右面,最後一個元素開始計算的,右面的第一個爲0,越靠左負數依次減一
剪接的元素數組
,原數組變化
,索引從0開始/*參數爲0個*/ var a = ['a','b','c','d','e']; a.splice()//返回[] a:["a", "b", "c", "d", "e"] 截個空數組。 原數組沒變。 /*參數爲1個*/ var a = ['a','b','c','d','e']; a.splice(0);//['a','b','c','d','e']; a:[]//原數組清空[]。從第一位開始截取,長度默認數組長度。 var a = ['a','b','c','d','e']; a.splice(2);//返回["c", "d", "e"] 原數組a:["a", "b"] /*參數是2個*/ //第一參數是索引(從0開始),第二是長度 var a = ['a','b','c','d','e']; a.splice(0,2);//["a", "b"] a:["c", "d", "e"] a.splice(0,2);//["c", "d"] a:["e"] var a = ['a','b','c','d','e']; a.splice(0,1);//["a"] a:["b", "c", "d", "e"] 同shift前刪除 var a = ['a','b','c','d','e'] a.splice(a.length-1,1)l//["e"] a:["a", "b", "c", "d"] 同pop前刪除 var arr=[1,3,5,777,'e'] arr.splice(2,1) //arr:[1, 3, 777, "e"] 能夠刪除數組的隨便的那個元素!! /*參數大於2個*/ //splice(start,deleteCount,val1,val2,...):從start位置開始刪除deleteCount項,並從該位置起插入val1,val2,... var a = ['a','b','c','d','e']; a.splice(3,1,10,21,238,99);//["d"] a:["a", "b", "c", 10, 21, 238, 99, "e"] var a = ['a','b','c','d','e']; a.splice(a.length,100000000,88)//返回 [] 從最後元素後面的元素,截取長度任意個,確定是空 a:["a", "b", "c", "d", "e", 88] 同push後增長 var a = ['a','b','c','d','e']; a.splice(a.length,0,88)//返回 [] 從最後元素後面的元素,截取長度任意個,確定是空 a:["a", "b", "c", "d", "e", 88] 同push後增長 var a = ['a','b','c','d','e']; a.splice(0,0,88,99)//返回 [] 從第一個元素,截取長度0個 確定是空 a:[88, 99, "a", "b", "c", "d", "e"] 同unshift前增長
var a = ['a','b','c','d','e']; a.concat([88,99]);//["a", "b", "c", "d", "e", 88, 99] a:["a", "b", "c", "d", "e"] var b= [9999,10000] a.concat(b);// ["a", "b", "c", "d", "e", 9999, 10000] a:["a", "b", "c", "d", "e"]
//坑1:排序後,影響自己(而非生成新數組) //坑2:默認狀況下sort方法是按ascii字母順序排序的,而非咱們認爲是按數字大小排序 var arr5=[100,19,52,502]; arr5.sort(); console.log(arr5); //arr5:[100, 19, 502, 52] //用法3:改變默認比較數字大小來排序 加入function(a,b){return a-b} //疑問4:a,b 表明.. arguments[0]和arguments[1]// function compare2Val(a,b){return a-b} var arr6=[100,19,52,502]; arr6.sort(compare2Val); //調用 不須要傳參, console.log(arr6); //arr6: [19, 52, 100, 502] //調用 不須要傳參的本質 function compare2Argument(){return arguments[0]-arguments[1]} var arr7=[100,19,52,502]; arr7.sort(compare2Argument); //[19, 52, 100, 502] console.log(arr7); //arr6: [19, 52, 100, 502] /*************總比較次數結論**************/ //疑問5 總比較次數:n(n-1)/2 n爲數組長度 //答:1:各輪比較次數 的和 //答:2: (數組長度-1+數組長度-2+數組長度-3......+1) /* 例數組長度6 比較次數:5+4+3+2+1=15 例數組長度5 比較次數:4+3+2+1=10 例數組長度4 比較次數:3+2+1=6 //高中學的1+2+3+.....+n=? 答案: 設S=1+2+…+(n-1)+n, 則S=n+(n-1)+…+2+1 ∴2S=(1+n)+[2+(n-1)]+…+[(n-1)+2]+(n+1) =n(n+1) ∴S= n(n+1)/2, 即1+2+…+(n-1)+n= n(n+1)/2. */ //比較輪數:數組長度-1 每輪比較產生一個最大值放在數組最右,這個最大值不參與下輪比較 //當前輪比較次數:數組長度-當前輪數 /*************結論**************/ //輪數4()-1 3輪 //第一輪:4-1比較3次 [19,100,52,502]; [19,52,100,502]; [19,52,100,502]; 作3次比較 //第二輪:4-2 比較2次 拋棄502,--->[19,52,100,502]; [19,52,100,502]; 只作19 52 ,52 100的2次比較 //第三輪:4-3 比較1次 拋棄100,502--->[19,52,100,502]; 只作19 52 的1次比較 //5,開發中經常使用方式 //例:根據人的年齡排序 function person(name,age){ this.Name=name; this.Age=age } var personArray=[]; personArray.push(new person("LiKe",18)); personArray.push(new person("Tom",58)); personArray.push(new person("Lucy",22)); personArray.push(new person("Haimei",16)); function compareAge(a,b){ return a.Age-b.Age; } personArray.sort(compareAge); console.log(personArray);//Haimei LiKe Lucy Tom
ES5
函數Array.isArray(a)
判斷a是否爲爲真正的Array
Array.isArray([]) //true Array.isArray({}) //false Array.isArray(11) //false Array.isArray(null) //false Array.isArray(undefined) //false
Array.prototype.indexOf(e,i)``起始位置i爲可選
var arr=[1,5,7,'str','str','str',9,10] arr.indexOf('str')//3 arr.indexOf('str',4)//4 arr.indexOf('f');//-1
Array.prototype.lastIndexOf(e,i)``最後位置i爲可選,默認arr.length-1
var arr=[1,5,7,'str','str','str',9,10] arr.lastIndexOf('str')//5 arr.lastIndexOf('str',4)//4 這是重點
如下context,都是靈活設置回調函數的執行上下文
測試some(fn,context)
數組中是否存在符合~.條件的元素
some(fn(value,index,array){return ..},undefined)``undefined可選,能夠爲undefined,能夠靈活設置回調函數的執行上下文
,Array.prototype.some(fn,context)
var arr=[1,5,7,'str',[99]] arr.some(function(value,index,array){return Array.isArray(value)})//true //return「執行」的意思。 Array.isArray(value)「測試函數」的意思。「只要」元素value知足測試(測試返回true),some遍歷函數返回true arr.some(function(value,index,array){return typeof(value)=='string'})//true
Array.prototype.every(fn,context)
var aa=[[],[1]]; aa.every(function(currentValue,index,array)){return Array.isArray(currentValue)}//true var bb=['',[]]; bb.every(function(currentValue,index,array){return Array.isArray(currentValue)},undefined)//false
返回經過測試fn的元素數組
Array.prototype.filter(fn,context)
var arr=[1,5,7,'str','str','str',9,10] arr.filter(function(value,index,array){return typeof(value)=='number'})//[1, 5, 7, 9, 10]
Array.prototype.reduce(fn,context)
,prev, cur, index, array
注意函數的參數通常來說prev是從數組中第一個元素開始的,cur是第二個元素
.可是當你傳入初始值(initialValue)後,第一個prev將是initivalValue,cur將是數組中的第一個元素。
//預先知道:15+[6]=156 var values = [1,2,3,4,5,[6]]; var i = 0; var sum = values.reduce(function (prev, cur, index, array) { console.log('頭值:',prev, '當前值',cur,'比較次數:',++i,'cur的索引:',index);//prev第一次循環,爲第一個值。之後的循環的值,是邏輯出來算的 return prev + cur;//獲得的頭值,參與下次循環,賦值給prev。固然下次循環 頭值也會和下次的當前值進行此種邏輯(這裏是加) }); console.log(sum); /* 結果 頭值: 1 當前值 2 比較次數: 1 cur的索引: 1 頭值: 3 當前值 3 比較次數: 2 cur的索引: 2 頭值: 6 當前值 4 比較次數: 3 cur的索引: 3 頭值: 10 當前值 5 比較次數: 4 cur的索引: 4 頭值: 15 當前值 [6] 比較次數: 5 cur的索引: 5 156 */ /*第二個例子,參考張鑫旭的例子*/ var matrix = [ [1, 2], [3, 4], [5, 6] ]; // 二維數組扁平化 var flatten = matrix.reduce(function (previous, current) { console.log(previous);//2次循環 length-1 return previous.concat(current); }); console.log(flatten);//[1, 2, 3, 4, 5, 6] /* [1, 2] [1, 2, 3, 4] */ /*第三個例子,裏面用到了es6的of方法,將類數組,類數組變量轉變成數組。相似new Array*/ var matrix = [ 999, [3, 4], [5, 6] ]; // 二維數組扁平化 var flatten = matrix.reduce(function (previous, current) { if (!Array.isArray(previous)) { previous = Array.of(previous); } return previous.concat(current); }); console.log(flatten);//[999, 3, 4, 5, 6] /*第四個例子,2個參數 參考:http://www.jb51.net/article/60502.htm*/ var arr = ["apple","orange"]; function noPassValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); return prev + " " +next; }); } function passValue(){ return arr.reduce(function(prev,next){ console.log("prev:",prev); console.log("next:",next); prev[next] = 1; return prev; },{}); } console.log("No Additional parameter:",noPassValue()); console.log("----------------"); console.log("With {} as an additional parameter:",passValue()); /* prev: apple next: orange No Additional parameter: apple orange ---------------- prev: Object {} next: apple prev: Object {apple: 1} next: orange With {} as an additional parameter: Object {apple: 1, orange: 1} */ //第5個例子:統計一個數組中有多少個不重複的單詞 var arr = ["apple", "orange", "apple", "orange", "pear", "orange"]; function getWordCnt() { return arr.reduce(function (prev, next) { console.log(prev, next); prev[next] = (prev[next] + 1) || 1; //修改本次prev return prev;//返回的這個值,做爲下次循環的prev的值 ,在前面外面能夠將本次的prev變成任何類型 本質延伸到了initialValue設置的類型 }, {}); } console.log(getWordCnt()); Object {} "apple" Object {apple: 1} "orange" Object {apple: 1, orange: 1} "apple" Object {apple: 2, orange: 1} "orange" Object {apple: 2, orange: 2} "pear" Object {apple: 2, orange: 2, pear: 1} "orange" Object {apple: 2, orange: 3, pear: 1}
Array.prototype.reduceRight(r,v)
是Array.prototype.reduce的從右向左的版本。var matrix = [ 999, [3, 4], [5, 6] ]; var flatten = matrix.reduceRight(function (previous, current) { console.log(previous, current); if (!Array.isArray(previous)) { previous = Array.of(previous); } return previous.concat(current); }); /* [5, 6] [3, 4] [5, 6, 3, 4] 999 */
Array.prototype.forEach(fn,context)
,val, index, arr
[1, 2, 'str', ['a'], true].forEach(function (val, index, arr) { if (val) { console.log(val, index) } }) /* 1 0 2 1 str 2 ["a"] 3 true 4 */ {a:1,b:2}.forEach(function(val,index,obj){if(val){console.log(val)}})//object 報錯
Array.prototype.map(fn,context)
,因此在fn中必定有return,參數必須是val,index,array
。這個fn能夠是自定義,也能夠是js內置的方法好比Math.sqaure使用函數fn修改每一個元素
,按順序收集f的每一個返回值
,返回這個新組成的數組
。this
//參考:https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/map 第一:每項單詞轉換成對應的複數形式. function fuzzyPlural(single) { var result = single.replace(/o/g, 'e'); if( single === 'kangaroo'){ result += 'se'; } return result; } var words = ["foot", "goose", "moose", "kangaroo"]; console.log(words.map(fuzzyPlural)); // ["feet", "geese", "meese", "kangareese"] 第二:求數組中每一個元素的平方根 var numbers = [1, 4, 9]; var roots = numbers.map(Math.sqrt); /* roots的值爲[1, 2, 3], numbers的值仍爲[1, 4, 9] */ 第三:String 上使用 map 方法獲取字符串中每一個字符所對應的 ASCII 碼組成的數組: var map = Array.prototype.map var a = map.call("Hello World", function(x) { return x.charCodeAt(0); }) // a的值爲[72, 101, 108, 108, 111, 32, 87, 111, 114, 108, 100] 第四:一般狀況下,map 方法中的fn函數只須要接受一個參數,就是正在被遍歷的數組元素自己。但這並不意味着 map 只給fn傳了一個參數。這個思惟慣性可能會讓咱們犯一個很容易犯的錯誤。 // 下面的語句返回什麼呢: ["1", "2", "3"].map(parseInt); // 你可能覺的會是[1, 2, 3] // 但實際的結果是 [1, NaN, NaN] // 一般使用parseInt時,只須要傳遞一個參數.但實際上,parseInt能夠有兩個參數.第二個參數是進制數.能夠經過語句"alert(parseInt.length)===2"來驗證. // map方法在調用callback函數時,會給它傳遞三個參數:當前正在遍歷的元素, 元素索引, 原數組自己. // 第三個參數parseInt會忽視, 但第二個參數不會,也就是說,parseInt把傳過來的索引值當成進制數來使用.從而返回了NaN. /* //應該使用以下的用戶函數returnInt function returnInt(element){ return parseInt(element,10); } ["1", "2", "3"].map(returnInt); // 返回[1,2,3] *
權威指南定義es5
// Determine if o is an array-like object.斷定o是不是一個類數組對象 // Strings and functions have numeric length properties, but are 字符串和函數有length屬性,可是它們 // excluded by the typeof test. In client-side JavaScript, DOM text能夠用typeof檢測將其排除,在客戶端js中,DOM文本節點 // nodes have a numeric length property, and may need to be excluded 也有length屬性,須要額外判斷o.nodeType!=3將其排除 // with an additional o.nodeType != 3 test. function isArrayLike(o) { if (o && // o is not null, undefined, etc. o非null undefined等 typeof o === 'object' && // o is an object o是對象 isFinite(o.length) && // o.length is a finite number o.length是個有限數值 o.length >= 0 && // o.length is non-negative o.length是非負值 o.length===Math.floor(o.length) && // o.length is an integer o.length是整數 o.length < 4294967296) // o.length < 2^32 o.length小於2^32 return true; // Then o is array-like else return false; // Otherwise it is not //不然它不是類數組 }
1:是{ 含有length鍵值對}2:[]都是類數組
//1:{ 含有length屬性的鍵值對} isArrayLike({qq:"aa",ww:"bbb",ss:"ccc",length:3})//true isArrayLike({"0":"aa",1:"bbb",2:"ccc",length:3})//true 特殊的類數組 //2:[]普通數組 isArrayLike([])//true
像數組同樣使用類數組(對象的屬性是「數值」字符串,'0' '1' '2' '3'....)
/* 由於這些"{ 含有length屬性的鍵值對}"類數組對象,不是經過new Array()構造函數構造出來的,因此這些不具有Array的原型方法。 可是咱們可使用改變做用域的方式來使用,[].map.call({},fn),[].slice.call({},..)等數組方法 若是想一想數組同樣使用它們,除了加上length屬性,須要這樣作: 須要保證這個對象的屬性必須是「數值」字符串,'0' '1' '2' '3'.... */ [].map.call({0:"aa",1:"bbb",2:"ccc",length:3},function(val){return val+"ooooooo"})//["aaooooooo", "bbbooooooo", "cccooooooo"] //常使用的功能:類數組對象轉化爲數組 [].slice.call({0:"aa",1:"bbb",2:"ccc",length:3},0)//["aa", "bbb", "ccc"]
/* 注意: 函數的內置對象arguments自己就是類數組,自己不能使用Array的原型實例方法,但能夠經過call等改變做用域的方式來使用; */ //arguments a(1,"2") function a(){ console.log(arguments);//[1, "2"],這裏打印出的雖然是[],看上去是數組,可是展開的以下圖,和普通數組不同。 //console.log(arguments.slice())//這樣會報錯: Uncaught TypeError: arguments.slice is not a function console.log([].slice.call(arguments));//[1, "2"] } console.log([].slice.call({0:"a",1:"bbb",2:"ccc",str:"str",str2:"str2",length:5}))//slice會把屬性不爲數字的類數組去掉 //NodeList var falseArr=document.getElementsByTagName('div'); for(item in falseArr)console.log(item)//能夠看到,item是 0 1 2 3...還有一些 id class等,證實NodeList是類數組 //falseArr.slice()//報錯 console.log([].slice.call(falseArr))
截圖
var str="asfwefwgw"; for(i=0; i<str.length;i++){console.log(i)} for(i=0; i<str.length;i++){console.log(str[i])}
//特殊類數組(鍵是數字) var o={"0":"aa",1:"bbb",2:"ccc",length:3};Array.from(o);//["aa", "bbb", "ccc"] //通常類數組 var o={qq:"aa",ww:"bbb",ss:"ccc",length:3};Array.from(o);//[undefined, undefined, undefined]
//類數組nodeList不能直接使用數組實例方法,要call apply改變做用域才能夠 var nodes=document.getElementsByTagName('a'); // nodes.forEach(function(val,key){console.log(key);})//nodes.forEach is not a function //es5 //Array.prototype.forEach.call ,[].forEach.call [].forEach.call(nodes,function(val,key){console.log(key);}) //es6 var nodesArray=Array.from(nodes); nodesArray.forEach(function(val,key){console.log(key);})
//類數組arguments不能直接使用數組實例方法,要call apply改變做用域才能夠 function foo(){ //arguments.forEach(function(val,index){console.log(index)})//arguments.forEach is not a function Array.prototype.forEach.call(arguments,function(val,index){console.log(index)})//1,2,3 Array.from(arguments).forEach(function(val,index){console.log(index)})//1,2,3 } foo(1,2,3)
//字符串
//Set
//Map
if (typeof Array.prototype.forEach != "function") { Array.prototype.forEach = function (fn, context) { for (var k = 0, length = this.length; k < length; k++) { if (typeof fn === "function" && Object.prototype.hasOwnProperty.call(this, k)) fn.call(context, this[k], k, this); } }; } if (typeof Array.prototype.map != "function") { Array.prototype.map = function (fn, context) { var arr = []; if (typeof fn === "function") { for (var k = 0, length = this.length; k < length; k++) { arr.push(fn.call(context, this[k], k, this)); } } return arr; }; } if (typeof Array.prototype.filter != "function") { Array.prototype.filter = function (fn, context) { var arr = []; if (typeof fn === "function") { for (var k = 0, length = this.length; k < length; k++) { fn.call(context, this[k], k, this) && arr.push(this[k]); } } return arr; }; } if (typeof Array.prototype.some != "function") { Array.prototype.some = function (fn, context) { var passed = false; if (typeof fn === "function") { for (var k = 0, length = this.length; k < length; k++) { if (passed === true) break; passed = !!fn.call(context, this[k], k, this); } } return passed; }; } if (typeof Array.prototype.every != "function") { Array.prototype.every = function (fn, context) { var passed = true; if (typeof fn === "function") { for (var k = 0, length = this.length; k < length; k++) { if (passed === false) break; passed = !!fn.call(context, this[k], k, this); } } return passed; }; } if (typeof Array.prototype.indexOf != "function") { Array.prototype.indexOf = function (searchElement, fromIndex) { var index = -1; fromIndex = fromIndex * 1 || 0; for (var k = 0, length = this.length; k < length; k++) { if (k >= fromIndex && this[k] === searchElement) { index = k; break; } } return index; }; } if (typeof Array.prototype.lastIndexOf != "function") { Array.prototype.lastIndexOf = function (searchElement, fromIndex) { var index = -1, length = this.length; fromIndex = fromIndex * 1 || length - 1; for (var k = length - 1; k > -1; k-=1) { if (k <= fromIndex && this[k] === searchElement) { index = k; break; } } return index; }; } if (typeof Array.prototype.reduce != "function") { Array.prototype.reduce = function (callback, initialValue ) { var previous = initialValue, k = 0, length = this.length; if (typeof initialValue === "undefined") { previous = this[0]; k = 1; } if (typeof callback === "function") { for (k; k < length; k++) { this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this)); } } return previous; }; } if (typeof Array.prototype.reduceRight != "function") { Array.prototype.reduceRight = function (callback, initialValue ) { var length = this.length, k = length - 1, previous = initialValue; if (typeof initialValue === "undefined") { previous = this[length - 1]; k--; } if (typeof callback === "function") { for (k; k > -1; k-=1) { this.hasOwnProperty(k) && (previous = callback(previous, this[k], k, this)); } } return previous; }; }
參考:
MDN: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array
http://www.zhangxinxu.com/wordpress/2013/04/es5%E6%96%B0%E5%A2%9E%E6%95%B0%E7%BB%84%E6%96%B9%E6%B3%95/