本文目錄
-
- 數組的遍歷
- 1.1 for in
- 1.2 for..of 循環
- 1.3 for 循環
- 1.4 array.forEach() 方法
-
- 數組的映射
- 2.1 Array.map()方法
- 2.2 Array.from()方法
-
- 數組簡化
- 3.1 Array.reduce() 方法
-
- 數據連接
- 4.1 array.concat() 方法
- 4.2 展開操作符號
-
- 數組截取
- 5.1 array.slice() 方法
-
- 數組拷貝
- 6.1 展開操作符號
- 6.2 array.concat()方法
-
- 數組查找
- 7.1 array.includes() 方法
- 7.2 array.find() 方法
- 7.3 array.indexOf() 方法
- 7.4 array.every() 方法
- 7.5 array.some() 方法
-
- 數組過濾
- 8.1 array.filter() 方法
-
- 數組插入
- 9.1 array.push() 方法
- 9.2 array.unshift() 方法
- 9.3 展開操作符號
-
- 刪除數組元素
- 10.1 array.pop() 方法
- 10.2 array.shift() 方法
- 10.3 array.splice() 方法
-
- 清空數組
- 11.1 array.length屬性
- 11.2 array.splice() 方法
-
- 填充數組
- 12.1 array.fill() 方法
- 12.2 Array.from() 函數
-
- 數組扁平化
- 13.1 array.flat()方法
-
- 數組的排序
- 14.1 array.sort() 方法
- 14.2 reverse()
-
- 數組的轉換
- 15.1 toString()
- 15.2 join()
- 16.數組的變異方法和非變異方法
1. 數組的遍歷
1.1 for in
for in是個兩用方法
可以用來遍歷數組,也可以用來遍歷對象
多數用來遍歷對象,效率比較低
首先遍歷對象
let person={name:"老王",age:23,city:"大唐"}
let text=""
for (let i in person){
text+=person[i]
}
輸出結果為:老王23大唐
其次在嘗試一些數組
let arry=[1,2,3,4,5]
for (let i in arry){
console.log(arry[i])
}
能輸出出來,輸出出來的是下標,證明也是可以的。
1.2 for..of 循環
for in循環看似完美,但實際使用中除了循環對象,基本不會用來循環數組。因為es6提供了一個更完美的數組循環方法:for..of
避免了for in的所有缺點,可以使用break,continue和return,
不僅支持數組的遍歷,還可以遍歷類似數組的對象,還支持字符串的遍歷
支持Map和Set對象遍歷
for..of 沒法直接去遍歷對象,但是遍歷數組的時候可以直接獲得每一項,而不是像for...in那樣只是拿到下標
for(const item of items)循環遍歷數組項,如下所示遍歷colors列表:
const colors = ['blue', 'green', 'white'];
for (const color of colors) {
console.log(color);
}
// 'blue'
// 'green'
// 'white'
提示:
可以隨時使用break語句停止遍歷。
1.3 for 循環
for(let i; i < array.length; i++)循環使用遞增的索引變量遍歷數組項。
for通常需要在每個循環中遞增index 變量
const colors = ['blue', 'green', 'white'];
for (let index = 0; index < colors.length; index++) {
const color = colors[index];
console.log(color);
}
// 'blue'
// 'green'
// 'white'
index變量從0遞增到colors.length-1。此變量用于按以下索引訪問項:colors [index]。
提示
for循環也可以隨時使用break語句停止遍歷。
1.4 array.forEach() 方法
array.forEach(callback)方法通過在每個數組項上調用callback函數來遍歷數組項。
在每次遍歷中,都使用以下參數調用callback(item [, index [, array]]):當前遍歷項,當前遍歷索引和數組本身。
const colors = ['blue', 'green', 'white'];
colors.forEach(function callback(item, i) {
console.log(item, i);
});
// 'blue', 0
// 'green', 1
// 'white', 2
**forEach特性:
- 不能中斷array.forEach()迭代(沒有return,就算加上也沒用)
- item參數代表循環當前項,必傳
- 只能用來循環數組
- 沒有返回值(undefined)
- 不影響原來的數組
2. 數組的映射
2.1 Array.map()方法
array.map(callback) 方法通過在每個數組項上使用callback調用結果來創建一個新數組。
在每個遍歷中的callback(item[, index[, array]])使用參數調用:當前項、索引和數組本身,并應該返回新項。
如下所示對每個數組元素都遞增 1:
const numbers = [0, 2, 4];
const newNumbers = numbers.map(function increment(number) {
return number + 1;
});
newNumbers; // => [1, 3, 5]
提示:
array.map()創建一個新的映射數組,而不改變原始數組。
2.2 Array.from()方法
Array.from(arrayLike[, callback])方法通過在每個數組項上使用callback 調用結果來創建一個新數組。
在每個遍歷中callback(item[, index[, array]])使用參數調用:當前項、索引和數組本身并且應該返回新項。
如下所示咱們對每個數組元素都遞增 1:
const numbers = [0, 2, 4];
const newNumbers = Array.from(numbers,
function increment(number) {
return number + 1;
}
);
newNumbers; // => [1, 3, 5]
提示:
Array.from()創建一個新的映射數組,而不改變原始數組。
Array.from()更適合從類似數組的對象進行映射。
在實際項目開發中,我們通過使用Array.from()將類數組對象轉換為真正數組
let arrayLike = {
0: 'tom',
1: '65',
2: '男',
3: ['jane','john','Mary'],
'length': 4
}
let arr = Array.from(arrayLike)
console.log(arr) // ['tom','65','男',['jane','john','Mary']]
那么,如果將上面代碼中length屬性去掉呢?實踐證明,答案會是一個長度為0的空數組。
這里將代碼再改一下,就是具有length屬性,但是對象的屬性名不再是數字類型的,而是其他字符串型的,代碼如下:
let arrayLike = {
'name': 'tom',
'age': '65',
'sex': '男',
'friends': ['jane','john','Mary'],
length: 4
}
let arr = Array.from(arrayLike)
console.log(arr) // [ undefined, undefined, undefined, undefined ]
會發現結果是長度為4,元素均為undefined的數組
由此可見,要將一個類數組對象轉換為一個真正的數組,必須具備以下條件:
- 1、該類數組對象必須具有length屬性,用于指定數組的長度。如果沒有length屬性,那么轉換后的數組是一個空數組。
- 2、該類數組對象的屬性名必須為數值型或字符串型的數字
注: 該類數組對象的屬性名可以加引號,也可以不加引號
3. 數組簡化
3.1 Array.reduce() 方法
array.reduce(callback[, initialValue])通過調用callback 函數來將數組簡化為一個值。
在每次遍歷中的callback(accumulator, item[, index[, array]])使用用參數調用的:累加器,當前項,索引和數組本身且應該返回累加器。
示例是對數字數組求和:
const numbers = [2, 0, 4];
function summarize(accumulator, number) {
return accumulator + number;
}
const sum = numbers.reduce(summarize, 0);
sum; // => 6
第一步,將accumulator 初始化為0。然后,對每個累加數字和的數組項調用summary函數。
提示:
如果沒有使用 initialValue 來設置初始值,則默認使用0來作為初始值。
4. 數據連接
4.1 array.concat() 方法
array.concat(array1[, array2, ...])將一個或多個數組連接到原始數組。如下所示,連接兩個數組:
const heroes = ['小智', '前端小智'];
const villains = ['老王', '小三'];
const everyone = heroes.concat(villains);
everyone // ["小智", "前端小智", "老王", "小三"]
提示:
concat()創建一個新的數組,而不改變原來的數組
array.concat(array1 [,array2,...]) 接受多個要連接的數組。
4.2 展開操作符號
咱們將展開操作符與數組字面量一起使用來連接數組:[...array1, ...array2]。
const heroes = ['小智', '前端小智'];
const villains = ['老王', '小三'];
const names = [...heroes, ...villains];
names; // ["小智", "前端小智", "老王", "小三"]
提示
[...arr1, ...arr2, ...arrN]:可以使用展開運算符連接所需數量的數組。
5. 數組截取
5.1 array.slice() 方法
array.slice([fromIndex [,toIndex]])返回數組的一個片段,該片段從fromIndex開始,以toIndex結尾(不包括toIndex本身)。fromIndex可選參數默認為0,toIndex可選參數默認為array.length。
const names = ["小智", "前端小智", "老王", "小三"]
const heroes = names.slice(0, 2)
const villains = names.splice(2)
heroes // ["小智", "前端小智"]
villains // ["老王", "小三"]
提示:
array.slice() 創建一個新數組,而不改變原始數組。
6. 數組拷貝
6.1 展開操作符號
拷貝數組的一種簡單方法是使用展開運算符:const clone = [... array],如下所示,拷貝 colors 數組:
const colors = ['white', 'black', 'gray'];
const clone = [...colors];
clone; // => ['white', 'black', 'gray']
colors === clone; // => false
提示:
[...array] 創建一個淺拷貝。
6.2 array.concat()方法
[].concat(array)是另一種拷貝數組的方法。
const colors = ['white', 'black', 'gray'];
const clone = [].concat(colors);
clone; // => ['white', 'black', 'gray']
colors === clone; // => false
提示:
[].concat(array) 創建一個淺拷貝。
6.3 array.slice() 方法
array.slice())是另一種拷貝數組的方法。
const colors = ['white', 'black', 'gray'];
const clone = colors.slice();
clone; // => ['white', 'black', 'gray']
colors === clone; // => false
提示:
colors.slice() 創建一個淺拷貝。
7. 數組查找
7.1 array.includes() 方法
array.includes(itemToSearch [,fromIndex])返回一個布爾值,array 是否包含itemToSearch。 可選參數fromIndex,默認為0,表示開始搜索的索引。如下所示:判斷2和99是否存在于一組數字中:
const numbers = [1, 2, 3, 4, 5];
numbers.includes(2); // => true
numbers.includes(99); // => false
7.2 array.find() 方法
array.find(predicate) 方法返回數組中滿足提供的測試函數的第一個元素的值。否則返回 undefined。
如下所示,找到數組中的第一個偶數:
const numbers = [1, 2, 3, 4, 5];
function isEven(number) {
return number % 2 === 0;
}
const evenNumber = numbers.find(isEven);
evenNumber; // => 2
7.3 array.indexOf() 方法
array.indexOf(itemToSearch[, fromIndex]) 返回array中第一個出現的itemToSearch的索引。默認為0的可選參數fromIndex表示開始搜索的索引。
如下所示,找到前端小智的索引:
const names = ["小智", "前端小智", "老王", "小三"]
const index = names.indexOf('前端小智')
index // 1
提示:
如果找不到該項,則array.indexOf(itemToSearch)返回-1
array.findIndex(predicate)是使用predicate函數查找索引的替代方法。
7.4 array.every() 方法
如果每個項都通過predicate 檢查,則array.every(predicate)返回true。
在每個遍歷predicate(item[, index[, array]])上,用參數調用predicate 函數:當前遍歷項、索引和數組本身。
如下所示,確定數組是否只包含偶數:
const evens = [0, 2, 4, 6];
const numbers = [0, 1, 4, 6];
function isEven(number) {
return number % 2 === 0;
}
evens.every(isEven); // => true
numbers.every(isEven); // => false
7.5 array.some() 方法
如果每個項只要一下通過predicate 檢查,則array.every(predicate)返回true。
在每個遍歷predicate(item[, index[, array]])上,用參數調用predicate 函數:當前遍歷項、索引和數組本身。
如下所示:確定數組是否至少包含一個偶數:
const numbers = [1, 5, 7, 10];
const odds = [1, 3, 3, 3];
function isEven(number) {
return number % 2 === 0;
}
numbers.some(isEven); // => true
odds.some(isEven); // => false
some和every總結:
some() 方法會依次執行數組的每個元素:
如果有一個元素滿足條件,則表達式返回true , 剩余的元素不會再執行檢測。
如果沒有滿足條件的元素,則返回false。
every() 方法使用指定函數檢測數組中的所有元素:
如果數組中檢測到有一個元素不滿足,則整個表達式返回 false ,且剩余的元素不會再進行檢測。
如果所有元素都滿足條件,則返回 true。
some和every都不會對空數組進行檢測,some和every的提前返回可以提高代碼運行效率,但是如果不想提高返回,而是想要遍歷執行所有項,則需要使用map方法
8. 數組過濾
8.1 array.filter() 方法
array.filter(predicate)方法創建一個新數組, 其包含通過所提供函數實現的測試的所有元素。
在每個遍歷predicate(item[, index[, array]])上,用參數調用predicate 函數:當前遍歷項、索引和數組本身。
如下所示:將一個數組過濾為僅包含偶數:
const numbers = [1, 5, 7, 10];
function isEven(number) {
return number % 2 === 0;
}
const evens = numbers.filter(isEven);
evens; // => [10]
提示:
array.filter() 創建一個新數組,而不改變原始數組。
filter的四個用法總結:
①.刪除重復的值
const numbers = [3, 12, 54, 12, 4, 4, 3, 12, 16];
const filteredNumbers = numbers.filter((number, index) => numbers.indexOf(number) === index);
console.log(filteredNumbers); // [3, 12, 54, 4, 16]
我們使用回調函數的第二個參數,它是當前元素的索引。
在這里,我們將indexOf()函數返回的索引與當前元素的實際索引進行比較。如果它們不同,則當前元素為重復值。
以上面的代碼段中的數組為例。當實際索引為時3,相鄰元素的值為12。但是,如果我們使用indexOf()該元素,則返回的索引是1因為該元素12首次出現在index處1。因此12是重復值之一。
②.刪除無效值
無效值被認為是可能導致錯誤和意外行為的值。
以年齡為例。如果年齡是定義的數字,則該年齡有效。
現在,我們要求過濾所有有效年齡的人,請看下面的代碼。
const people = [
{ name: ‘Amy’, gender: ‘female’, age: ‘28’ },
{ name: ‘James’, gender: ‘male’, age: 13 },
{ name: ‘Victor’, gender: ‘male’, age: null },
{ name: ‘David’, gender: ‘male’, age: 28 },
{ name: ‘Simon’, gender: ‘male’, age: undefined },
{ name: ‘Anna’, gender: ‘female’, age: 21 },
{ name: ‘Jane’, gender: ‘female’, age: NaN }
];
const filteredPeople = people.filter(person => person.age !== undefined && typeof person.age === ‘number’ && !isNaN(person.age));
console.log(filteredPeople);
// [{ name: ‘James’, gender: ‘male’, age: 13 }, { name: ‘David’, gender: ‘male’, age: 28 }, { name: ‘Anna’, gender: ‘female’, age: 21 }]
③.過濾數字數組
這是最簡單的用法。
假設你有一個數字數組,并且只需要從該數組中提取奇數。
const numbers = [23, 54, 1, 3, 72, 28];
const oddNumbers = numbers.filter(number => number % 2 !== 0);
console.log(oddNumbers); // [23, 1, 3]
或者你想創建一個包含給定數組中所有素數的新數組。
const isPrime = number => {
if (number === 1) return false;
if (number === 2) return true;
for (let i = 2; i < number; i++) {
if (number % i === 0) return false;
}
return true;
}
const numbers = [23, 54, 1, 3, 72, 28];
const oddNumbers = numbers.filter(isPrime);
console.log(oddNumbers); // [23, 3]
④.過濾對象數組
盡管一個對象比數字更復雜,但是使用filter()仍然可以保持簡單。
例如,假設我們有很多人。要求是找到所有年齡大于18歲的人。
const people = [
{ name: ‘Amy’, gender: ‘female’, age: 28 },
{ name: ‘James’, gender: ‘male’, age: 13 },
{ name: ‘Victor’, gender: ‘male’, age: 17 },
{ name: ‘David’, gender: ‘male’, age: 28 },
{ name: ‘Simon’, gender: ‘male’, age: 33 }
];
const filteredPeople = people.filter(person => person.age > 18);
console.log(filteredPeople);
// [{ name: ‘Amy’, gender: ‘female’, age: 28 }, { name: ‘David’, gender: ‘male’, age: 28 }, { name: ‘Simon’, gender: ‘male’, age: 33 }]
如果是,我們需要找出所有年齡大于18歲的女性,這時,我們只需向回調函數添加一個附加條件即可。
const people = [
{ name: ‘Amy’, gender: ‘female’, age: 28 },
{ name: ‘James’, gender: ‘male’, age: 13 },
{ name: ‘Victor’, gender: ‘male’, age: 17 },
{ name: ‘David’, gender: ‘male’, age: 28 },
{ name: ‘Simon’, gender: ‘male’, age: 33 }
];
const filteredPeople = people.filter(person => person.age > 18 && person.gender === ‘female’);
console.log(filteredPeople);
// [{ name: ‘Amy’, gender: ‘female’, age: 28 }]
9. 數組插入
9.1 array.push() 方法
array.push(item1 [...,itemN]) 方法將一個或多個項追加到數組的末尾,并返回新的長度。
如下所示,在names 數組的末尾添加 '小智'
const names = ['小智']
names.push('前端小智')
names // ["小智", "前端小智"]
提示:
array.push() 會改變原數組
array.push(item1, item2, ..., itemN) 可以添加多個元素。
9.2 array.unshift() 方法
array.unshift(item1[..., itemN])方法將一個或多個項追加到數組的開頭,返回數組的新長度
const names = ['小智']
names.unshift('前端小智')
names // ["前端小智", "小智"]
提示:
array.unshift() 會改變原數組
array.unshift(item1, item2, ..., itemN) 可以添加多個元素。
9.3 展開操作符號
可以通過組合展開操作符和數組字面量以不可變的方式在數組中插入項。
在數組末尾追加一個項:
const names = ['小智', '大治']
const names2 = [...names, '王大冶']
names2 // ["小智", "大治", "王大冶"]
在數組的開頭追加一個項:
const names = ['小智', '大治']
const names2 = [
'王大冶',
...names
]
names2 // ["王大冶", "小智", "大治"]
在任何索引處插入元素:
const names = ['小智', '大治']
const indexToInsert = 1
const names2 = [
...names.slice(0, indexToInsert),
'前端小智',
...names.slice(indexToInsert)
]
names2 // ["小智", "前端小智", "大治"]
10. 刪除數組元素
10.1 array.pop() 方法
array.pop()方法從數組中刪除最后一個元素,然后返回該元素。如下所示,刪除colors數組的最后一個元素:
const colors = ['blue', 'green', 'black'];
const lastColor = colors.pop();
lastColor; // => 'black'
colors; // => ['blue', 'green']
提示:
array.pop() 會改變原數組。
10.2 array.shift() 方法
array.shift()方法從數組中刪除第一個元素,然后返回該元素。
const colors = ['blue', 'green', 'black'];
const firstColor = colors.shift();
firstColor; // => 'blue'
colors; // => ['green', 'black']
提示:
array.shift() 會改變原數組。
10.3 array.splice() 方法
array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]])從數組中刪除元素,并插入新的元素。
例如,咱們從索引1處刪除2個元素:
const names = ['張三', '李四', '王五', '趙六']
names.splice(1, 2)
names // => ["張三", "趙六"]
names.splice(1,2)刪除元素'張三'和'王五'。
names.splice() 可以插入新元素,而不是插入已刪除的元素。 咱們可以替換索引1處開始的的2個元素,然后插入一個新的元素 '小智':
const names = ['張三', '李四', '王五', '趙六']
names.splice(1, 2, '小智')
names // ["張三", "小智", "趙六"]
提示:
array.splice() 會改變原數組。
除數組的指定項,用delete也可以達到
var a = [1,2,3,4,5,6,7]
delete a[3]
console.log(a) //[1, 2, 3, empty,5, 6, 7]
但是原來的索引還是沒變,索引3被刪掉了,但依舊后面的索引4,5,6也還是保持原樣
這時候打印 a[3] ,結果是undefined
正常的方式應該用splice
var a = [1,2,3,4,5,6,7]
a.splice(3,1)
console.log(a)
這種方式的刪除才更加徹底
11. 清空數組
11.1 array.length屬性
array.length是保存數組長度的屬性。 除此之外,array.length是可寫的。
如果咱們寫一個小于當前長度的array.length = newLength,多余的元素從數組中移除。
如下所示:使用array.length = 0刪除數組中的所有項目:
const colors = ['blue', 'green', 'black'];
colors.length = 0;
colors; // []
11.2 array.splice() 方法
array.splice(fromIndex[, removeCount[, item1[, item2[, ...]]]])從數組中刪除元素,并插入新的元素。
如果removeCount參數被省略,那么array.splice()將刪除從fromIndex開始的數組的所有元素。咱們使用它來刪除數組中的所有元素:
const colors = ['blue', 'green', 'black'];
colors.splice(0);
colors; // []
12. 填充數組
12.1 array.fill() 方法
array.fill(value[, fromIndex[, toIndex]])用從fromIndex 到toIndex的值填充數組(不包括toIndex本身)。fromIndex可選參數默認為0,toIndex可選參數默認為array.length。
例如,使用用零值填充數組:
const numbers = [1, 2, 3, 4];
numbers.fill(0);
numbers; // => [0, 0, 0, 0]
不僅如此,還可以使用Array(length).fill(initial)來初始化特定長度和初始值的數組。
const length = 3;
const zeros = Array(length).fill(0);
zeros; // [0, 0, 0]
12.2 Array.from() 函數
Array.from() 可以初始化帶有對象的特定長度的數組:
const length = 4;
const emptyObjects = Array.from(Array(length), function() {
return {};
});
emptyObjects; // [{}, {}, {}, {}]
13. 數組扁平化
13.1 array.flat()方法
array.flat([depth])方法通過遞歸扁平屬于數組的項直到一定深度來創建新數組。 depth可選參數默認為1:
const arrays = [0, [1, 3, 5], [2, 4, 6]];
const flatArray = arrays.flat();
flatArray; // [0, 1, 3, 5, 2, 4, 6]
arrays 包含數字和數字數組的混合。 arrays.flat()對數組進行扁平,使其僅包含數字。
提示:
array.flat() 創建一個新數組,而不會改變原始數組。
14. 數組的排序
14.1 array.sort() 方法
array.sort([compare])方法對數組的元素進行排序。
可選參數compare(a, b)是一個自定義排序順的回調函數。如果比較compare(a, b)返回的結果:
如果 a小于b,在排序后的數組中a應該出現在b之前,就返回一個小于0的值。
如果a等于b,就返回0。
如果a大于b,就返回一個大于0的值。
如下所示,對數組 numbers 時行排序
const numbers = [4, 3, 1, 2];
numbers.sort();
numbers; // => [1, 2, 3, 4]
numbers.sort() 以升序對數字進行排序。
使用比較函數,讓偶數排在奇數前面:
const numbers = [4, 3, 1, 2];
function compare(n1, n2) {
if (n1 % 2 === 0 && n2 % 2 !== 0) {
return -1;
}
if (n1 % 2 !== 0 && n2 % 2 === 0) {
return 1;
}
return 0;
}
numbers.sort(compare);
numbers; // => [4, 2, 3, 1]
提示:
array.sort() 會改變原數組。
14.2 reverse()
此方法用于顛倒數組中元素的順序。第一個元素成為最后一個,最后一個元素將成為第一個。
···
const myAwesomeArray = ["e", "d", "c", "b", "a"]
myAwesomeArray.reverse()
// -------> Output : ['a', 'b', 'c', 'd', 'e']
···
15.數組的轉換
將數組轉換為字符串
15.1 toString()
JavaScript 方法 toString() 把數組轉換為數組值(逗號分隔)的字符串。
var fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
//結果為 Banana,Orange,Apple,Mango
15.2 join()
join()行為類似 toString(),但是參數可以規定分隔符
var fruits = ["Banana", "Orange","Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
//結果為 Banana * Orange * Apple * Mango
16.數組的變異方法和非變異方法
數組的7個變異方法:
push()
pop()
shift()
unshift()
splice()
sort()
reverse()
其他都是非變異的方法
splice是非常常用的數組變異方法
splice可以實現純添加,比如下面這樣
let a = [1,2,3,4]
a.splice(1,0,'xxx')
console.log(a) //[1, "xxx", 2, 3, 4]
splice也可以實現快速刪除數組指定的索引項
let a = [1, 2, 3, 4];
a.splice(1, 1);
console.log(a); //[1, 3, 4]
快速替換
let a = [1, 2, 3, 4];
a.splice(1, 1, "xxxx");
console.log(a); //[1, "xxxx", 3, 4]