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