JS中,陣列可以通過 Array 建構式或 [] 字面量的方式創建,陣列是一個特殊的物件,繼承自 Object 原型,但用 typeof 判斷時,并沒有一個特定的值,仍然回傳 'object',但使用 [] instanceof Array 回傳 true,這說明,JS中存在一個類陣列的物件,就像字串物件或 arguments 物件,arguments 物件不是陣列的實體,但仍然有 length 屬性,值也可以被索引,因此也可以像陣列一樣被回圈遍歷,
這篇文章中,我將盤點下定義在 Array 原型上的一些常用的方法,并逐一介紹其用法,
- 回圈 .forEach
- 斷言 .some,.every
- 連接與合并 .join,.concat
- 堆疊與佇列 .pop, .push, .shift, .unshift
- 模型映射 .map
- 過濾 .filter
- 排序 .sort
- 聚合 .reduce, .reduceRight
- 截取 .slice
- 洗掉插入 .splice
- 查找值 .indexOf
- 查找鍵 in 運算子
- 顛倒 .reverse

1.forEach()
forEach 對陣列的所有成員依次執行且只執行一次引數函式,引數函式包含以下3個引數:
- value 當前值
- index 當前位置,索引值
- array 當前陣列
進一步,可以傳遞一個可選引數用于指定函式里的 this 背景關系,
['_', 't', 'a', 'n', 'i', 'f', ']'].forEach(function (value, index, array) {
this.push(String.fromCharCode(value.charCodeAt() + index + 2))
}, out = [])
out.join('')
// <- 'awesome'
forEach的缺陷是既不能中斷回圈,也不能拋出例外,
2.some(), every()
這兩個方法類似“斷言”(assert),回傳一個布林值,表示判斷陣列成員是否符合某種條件,
類似于 forEach,同樣接受一個包含 value, index, and array的回呼函式作為引數,而且也可以指定 背景關系中的this,
some方法是只要一個成員的回傳值是true,則整個some方法的回傳值就是true,否則回傳false,
every方法是所有成員的回傳值都是true,整個every方法才回傳true,否則回傳false,
max = -Infinity
satisfied = [10, 12, 10, 8, 5, 23].some(function (value, index, array) {
if (value > max) max = value
return value < 10
})
console.log(max)
// <- 12
satisfied
// <- true
3.join() and concat()
這兩個方法容易搞混,join是將陣列內各個成員用分隔符連接成一個字串,分隔符默認是 ,,concat用于多個陣列的合并,它將新陣列的成員,添加到原陣列成員的后部,然后回傳一個新陣列,原陣列不變,
var a = { foo: 'bar' }
var b = [1, 2, 3, a]
var c = b.concat()
console.log(b === c)
// <- false
b[3] === a && c[3] === a
// <- true
4.pop, .push, .shift, and .unshift
每個人都知道往陣列末尾添加一個元素是用push方法,但你知道可以一次性添加多個元素嗎,像這樣 [].push('a', 'b', 'c', 'd', 'z').
pop是push方法的逆操作,去除陣列最后一個元素同時回傳這個元素,如果是空陣列則回傳 undefined,使用這兩個方法很容易實作 LIFO(last in first out) 堆疊結構,
function Stack () {
this._stack = []
}
Stack.prototype.next = function () {
return this._stack.pop()
}
Stack.prototype.add = function () {
return this._stack.push.apply(this._stack, arguments)
}
stack = new Stack()
stack.add(1,2,3)
stack.next()
// <- 3
相應的,我們可以通過 .unshift and .shift 實作一個 FIFO (first in first out)佇列,
function Queue () {
this._queue = []
}
Queue.prototype.next = function () {
return this._queue.shift()
}
Queue.prototype.add = function () {
return this._queue.unshift.apply(this._queue, arguments)
}
queue = new Queue()
queue.add(1,2,3)
queue.next()
// <- 1
使用 .shift (or .pop) 很容易用while回圈清空一個陣列,如下:
list = [1,2,3,4,5,6,7,8,9,10]
while (item = list.shift()) {
console.log(item)
}
list
// <- []
5.map()
map方法將陣列的所有成員依次傳入回呼函式,然后把每一次的執行結果組成一個新陣列回傳,
方法簽名類似于 forEach,.map(fn(value, index, array), thisArgument).
values = [void 0, null, false, '']
values[7] = void 0
result = values.map(function(value, index, array){
console.log(value)
return value
})
// <- [undefined, null, false, '', undefined × 3, undefined]
undefined × 3 表明了回呼函式不會在已洗掉或未賦值的成員執行,而是自己回傳包含在回傳陣列中,Map在映射或轉換陣列時非常有用,比如下面這個例子:
// casting
[1, '2', '30', '9'].map(function (value) {
return parseInt(value, 10)
})
// 1, 2, 30, 9
[97, 119, 101, 115, 111, 109, 101].map(String.fromCharCode).join('')
// <- 'awesome'
// a commonly used pattern is mapping to new objects
items.map(function (item) {
return {
id: item.id,
name: computeName(item)
}
})
6.filter()
filter方法用于過濾陣列成員,滿足條件的成員組成一個新陣列回傳,
使用類似于,.filter(fn(value, index, array), thisArgument).
[void 0, null, false, '', 1].filter(function (value) {
return value
})
// <- [1]
[void 0, null, false, '', 1].filter(function (value) {
return !value
})
// <- [void 0, null, false, '']
7.sort(compareFunction)
sort方法對陣列成員進行排序,默認是按照字典順序排序,排序后,原陣列將被改變,
像大多數的排序函式一樣,Array.prototype.sort(fn(a,b)) 接受一個回呼函式用于比較 a,b 的大小,而且為下面三種情況之一:
- return value < 0 if a comes before b
- return value =https://www.cnblogs.com/jiaoran/archive/2020/09/30/== 0 if both a and b are considered equivalent
- return value > 0 if a comes after b
[9,80,3,10,5,6].sort()
// <- [10, 3, 5, 6, 80, 9]
[9,80,3,10,5,6].sort(function (a, b) {
return a - b
})
// <- [3, 5, 6, 9, 10, 80]
8.reduce(), reduceRight()
Reduce函式一開始很難理解,這些函式會回圈陣列,從左向右 (.reduce) 或從右向左 (.reduceRight),每次回呼函式執行時會接受之前的部分結果,最侄訓傳值是單個聚合的值,
兩個方法具有相同的語法:
reduce(callback(previousValue, currentValue, index, array), initialValue)
previousValue 是上次回呼函式執行的回傳值,或者第一次執行時的初始值;currentValue 是當前值;index 是當前值位置;array 是執行reduce方法陣列的參考;initialValue 是初始值;
.reduce方法的一個典型應用場景是陣列成員求和:
Array.prototype.sum = function () {
return this.reduce(function (partial, value) {
return partial + value
}, 0)
};
[3,4,5,6,10].sum()
// <- 28
9.slice()
slice()方法用于提取目標陣列的一部分,回傳一個新陣列,原陣列不變,
arr.slice(start, end)
它的第一個引數為起始位置(從0開始,會包括在回傳的新陣列之中),第二個引數為終止位置(但該位置的元素本身不包括在內),如果省略第二個引數,則一直回傳到原陣列的最后一個成員,
與concat()類似,slice()如果沒有任何引數則回傳原陣列的淺拷貝,Array.prototype.slice可以用來將類陣列的物件轉換成真正的陣列,
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })
// <- ['a', 'b']
concat做不到,它會回傳一個包含傳入物件的陣列,
Array.prototype.concat.call({ 0: 'a', 1: 'b', length: 2 })
// <- [{ 0: 'a', 1: 'b', length: 2 }]
10.splice()
.splice 是我最喜歡的array原生陣列方法,它允許你在一次性在同一個位置洗掉、插入元素,注意:這個函式會改變原陣列,
var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]
var spliced = source.splice(3, 4, 4, 5, 6, 7)
console.log(source)
// <- [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ,13]
spliced
// <- [8, 8, 8, 8]
你可能注意到了,它會回傳被洗掉的元素,這個常用于回圈被洗掉的元素,你之前可能忘記了,
var source = [1,2,3,8,8,8,8,8,9,10,11,12,13]
var spliced = source.splice(9)
spliced.forEach(function (value) {
console.log('removed', value)
})
// <- removed 10
// <- removed 11
// <- removed 12
// <- removed 13
console.log(source)
// <- [1, 2, 3, 8, 8, 8, 8, 8, 9]
11.indexOf()、lastIndexOf()
indexOf方法回傳給定元素在陣列中第一次出現的位置,如果沒有出現則回傳-1,
var a = { foo: 'bar' }
var b = [a, 2]
console.log(b.indexOf(1))
// <- -1
console.log(b.indexOf({ foo: 'bar' }))
// <- -1
console.log(b.indexOf(a))
// <- 0
console.log(b.indexOf(a, 1))
// <- -1
b.indexOf(2, 1)
// <- 1
lastIndexOf方法回傳給定元素在陣列中最后一次出現的位置,如果沒有出現則回傳-1,
注意,這兩個方法不能用來搜索NaN的位置,即它們無法確定陣列成員是否包含NaN,
這是因為這兩個方法內部,使用嚴格相等運算子(===)進行比較,而NaN是唯一一個不等于自身的值,
12.in 運算子
in 用于查找 key 在一個陣列中是否存在,indexOf則是查找值,當然速度快于 indexOf.
var a = [1, 2, 5]
1 in a
// <- true, but because of the 2!
5 in a
// <- false
var a = [3, 7, 6]
1 in a === !!a[1]
// <- true
in 運算子跟把相應位置的值轉化為布林值類似,!! 運算式常用于將一個值取反然后再取反,這是一種高效的將真值轉為布林值的方式,
13.reverse()
reverse方法用于顛倒排列陣列元素,回傳改變后的陣列,注意,該方法將改變原陣列,
var a = ['a', 'b', 'c'];
a.reverse() // ["c", "b", "a"]
a // ["c", "b", "a"]
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/142400.html
標籤:其他
上一篇:vue組件遞回
下一篇:H5+ 操作手機日歷
