一、數(shù)組
1.棧方法 let a=[1,2,3,4,5] (后進(jìn)先出)
push 推入元素到數(shù)組的末尾奶栖,改變?cè)瓟?shù)組匹表,返回?cái)?shù)組的長度 alert(a.push(6)) / 6
pop 刪除數(shù)組最后一項(xiàng),改變?cè)瓟?shù)組宣鄙,返回刪除的項(xiàng) alert(a.pop()) / 5
2.隊(duì)列方法 let a=[1,2,3,4,5] (先進(jìn)先出)
shift 刪除數(shù)組的第一項(xiàng)袍镀,改變?cè)瓟?shù)組,返回刪除的項(xiàng) alert(a.shift()) /1
unshift 添加指定元素到數(shù)組的前端冻晤,改變?cè)瓟?shù)組苇羡,返回?cái)?shù)組長度 alert(a.unshift(1)) /6
3.重排序方法 let a=[1,2,3,4,5]
reverse 反轉(zhuǎn)數(shù)組項(xiàng)的順序,改變?cè)瓟?shù)組鼻弧,返回改變之后的數(shù)組 alert(a.reverse()) /[5,4,3,2,1]
sort 按升序排列數(shù)組項(xiàng)设江,轉(zhuǎn)成字符串再進(jìn)行比較锦茁,改變?cè)瓟?shù)組,返回改變之后的數(shù)組 alert([1,5,10,20].sort()) /[1,10,20,5]
ps:如果想實(shí)現(xiàn)排序可以用compare函數(shù)
function compare(value1,value2){
if(value1<value2){
return -1;
}else if(value1>value2){
return 1;
}else{
return 0;
}
}
let a=[1,5,10,20]
alert(a.sort(compare)) / [1,5,10,20]
4.操作方法 let a=[1,2,3,4,5]
concat 創(chuàng)建當(dāng)前數(shù)組的一個(gè)副本叉存,然后將接收到的參數(shù)添加至這個(gè)副本的末尾码俩,不改變?cè)瓟?shù)組,返回新構(gòu)建的數(shù)組
alert(a.concat(1,2,[3])) / [1,2,3,4,5,1,2,3]
slice 基于當(dāng)前數(shù)組中的一項(xiàng)或多項(xiàng)創(chuàng)建一個(gè)新數(shù)組歼捏,不改變?cè)瓟?shù)組稿存,返回新構(gòu)建的數(shù)組
alert(a.slice(1)) / [2,3,4,5] alert(a.slice(1,4)) [2,3,4] alert(a.slice(-2,-1)) / 4
splice 改變?cè)瓟?shù)組,返回刪除的項(xiàng)
傳兩個(gè)參的時(shí)候是刪除任意數(shù)量的項(xiàng) alert(a.splice(0,1)) / [1] alert(a) /[2,3,4,5]
傳三個(gè)參的時(shí)候瞳秽,第一個(gè)是從哪個(gè)索引值開始刪除瓣履,第二個(gè)參是刪除的個(gè)數(shù),第三參是從該索引處添加的參數(shù)
alert(a.splice(1,0,7)) / [] alert(a) / [1,7,2,3,4,5]
alert(a.splice(1,1,7)) / [2] alert(a) / [1,7,3,4,5]
5.位置方法 let a=[1,2,3,4,5,1,2,3,4]
indexOf alert(a.indexOf(4)) / 3 alert(a.indexOf(4,4)) / 8
lastIndexOf alert(a.lastIndexOf(4)) / 8 alert(a.lastIndexOf(4,4)) /3
6.迭代方法 (every,filter,map,forEach,some)
7.歸并方法 let a=[1,2,3,4,5]
reduce reduceRight
let value=a.reduce(function(prev,cur,index,array){return prev+cur}) alert(value) / 15
reduceRight方法一樣练俐,只是執(zhí)行的方法是從右到左
二拂苹、字符串 slice/substring/substr/trim/toLocaleLowerCase/toLocaleUpperCase/
let a="hello world"
alert(a.slice(3)) / "lo world"
alert(a.substring(3)) / "lo world"
alert(a.substr(3)) / "lo world"
alert(a.slice(3,7)) / "lo w"
alert(a.substring(3,7)) / "lo w"
alert(a.substr(3,7)) / "lo worl"
alert(a.slice(-3)) / "rld"
alert(a.substring(-3)) / "hello world"
alert(a.substr(-3)) / "rld"
alert(a.indexOf("o")) / 4
alert(a.lastIndexOf("o")) / 7
alert(a.indexOf("o",6)) / 從索引值6開始往后查找o / 7
alert(a.lastIndexOf("o",6)) / 從索引值6開始往前查找o /4
let a=" hello world "
alert(a.trim()) / "hello world"
let a="hello world"
alert(a.toLocaleLowerCase()) /"hello world"
alert(a.toLocaleUpperCase()) / "HELLO WORLD"
字符串模式匹配方法replace(),可以接兩個(gè)參數(shù),第一個(gè)參可以是字符串和正則表達(dá)式痰洒,第二個(gè)參可以是字符串和函數(shù)
let text="cat,bat,sat,fat"
alert(text.replace('at','ond')) / "cond,bat,sat,fat"
alert(text.replace(/at/g,'ond')) / 'cond,bond,sond,fond'