陣列 的幾種常見方法

2021-09-29 11:09:13 字數 3318 閱讀 8867

unshift()

新增,將要給定的數值新增到陣列的開頭

var arr =

["西瓜"

,"蘋果"

,"雪梨"

,"香蕉"];

arr.

unshift

("桃子"

,"哈密瓜");

//["桃子","哈密瓜","西瓜","蘋果","雪梨","香蕉"]

console.

log(arr)

;

shift() 方法

從陣列中刪除第乙個元素,並返回該元素的值。此方法更改陣列的長度。

從陣列中刪除的元素,如果組數為空側返回undefined

var a =[1

,2,3

];var b = a.

shift()

;console.

log(a)

;//[2,3]

console.

log(b)

;// 1

push()

新增,將要給定的數值新增到陣列的後頭

var arr =

["西瓜"

,"蘋果"

,"雪梨"

,"香蕉"];

arr.

push

("桃子"

,"哈密瓜");

//["桃子","哈密瓜","西瓜","蘋果","雪梨","香蕉"]

pop()方法

從陣列中刪除最後乙個元素,並返回該元素的值。此方法更改陣列的長度。

var a =[1

,2,3

];a.pop()

;console.

log(a)

;//[1,2]

splice(從1開始], (長度[不刪除就為0, 刪除幾個就是幾個]), 元素a,元素b)

例如 arr.splice(1, 1, 「老安」,「平板」);

1.想從哪乙個後面開始新增就寫幾

var arr =

["西瓜"

,"蘋果"

,"雪梨"

,"香蕉"];

arr.

splice(1

,0,"桃子"

)//["西瓜","桃子","蘋果","雪梨","香蕉"]

arr.

splice(1

,0,"聖尼果"

,"西紅柿"

)// ["西瓜","聖尼果","西紅柿","桃子","蘋果","雪梨","香蕉"]

2.從第一位後刪除蘋果,新增"聖尼果",「西紅柿」

var arr =

["西瓜"

,"蘋果"

,"雪梨"

,"香蕉"];

arr.

splice(1

,1,"聖尼果"

,"西紅柿"

)// ["西瓜","聖尼果","西紅柿","雪梨","香蕉"]

concat()合併

將兩個陣列合併

var arr1 =

['a'

,'b'

,'c'];

var arr2 =

['d'

,'e'

,'f'];

//合併

console.

log(arr1.

concat

(arr2));

//["a", "b", "c", "d", "e", "f"]

//方法一

console.

log(arr1.

concat

("j"

,arr2));

//["a", "b", "c", "j", "d", "e", "f"]

console.

log(arr1.

concat

("j"

+arr2));

// ["a", "b", "c", "jd,e,f"]

//方法二

console.

log(arr1+arr2.

concat

("j"))

;//拼接在一起a,b,cd,e,f,j

join()

將陣列(或乙個類陣列物件)的所有元素變成字串

var arr2=

["王白菜"

,"牛春"

,"野老多"];

console.

log(arr2.

join

('-'))

;//王白菜-牛春-野老多

reverse()

是將陣列順序顛倒

var arr =

['one'

,'two'

,'three'];

var reversed = arr.

reverse()

; console.

log(arr)

;//["three", "two", "one"]

sort()排序

var arr =[1

,30,22

,49,31

,21];

arr.

sort()

;console.

log(arr)

;//[1, 21, 22, 30, 31, 49]

arr.

sort

(function

(a, b)

);

filter()

陣列的過濾

//	例子:過濾出陣列中單詞長度大於6的單詞

let words =

['spr'

,'limit'

,'like'

,'destruction'

,'present'];

let result = words.

filter

(word => word.length >6)

;console.

log(result)

//["destruction", "present"]

JS陣列去重的幾種常見方法

js陣列去重的幾種常見方法 一 簡單的去重方法 最簡單陣列去重法 新建一新陣列,遍歷傳入陣列,值不在新陣列就push進該新陣列中 ie8以下不支援陣列的indexof方法 function uniq array return temp var aa 1,2,2,4,9,6,7,5,2,3,5,6,5...

JS陣列去重的幾種常見方法

方法一 最簡單陣列去重法 新建一新陣列,遍歷傳入陣列,值不在新陣列就push進該新陣列中 ie8以下不支援陣列的indexof方法 function uniq array return temp var aa 1,2,2,4,9,6,7,5,2,3,5,6,5 console.log uniq aa...

JS陣列去重的幾種常見方法

js陣列去重的幾種常見方法 一 簡單的去重方法 最簡單陣列去重法 新建一新陣列,遍歷傳入陣列,值不在新陣列就push進該新陣列中 ie8以下不支援陣列的indexof方法 function uniq array return temp var aa 1,2,2,4,9,6,7,5,2,3,5,6,5...