1. 添加删除数组元素
(1) push()
向数组的末尾添加一个或更多元素,并返回新的长度。
push(item1, item2, ..., itemX)
- 新元素将添加在数组的末尾
- 此方法改变数组的长度
- 返回数组新的长度
let fruits = ["a", "b", "c", "d"];
let l = fruits.push("e", "f", "g")
console.log(l); // 7
console.log(fruits); // ['a', 'b', 'c', 'd', 'e', 'f', 'g']
(2) pop()
删除数组的最后一个元素并返回删除的元素
array.pop()
-
此方法改变数组的长度!
-
数组元素可以是一个字符串,数字,数组,布尔,或者其他对象类型。
-
返回删除的元素
let fruits = ["a", "b", "c", "d"];
let n = fruits.pop()
console.log(n); // 'd'
console.log(fruits); // ['a', 'b', 'c']
(3) shift()
删除并返回数组的第一个元素
array.shift()
- 此方法改变数组的长度!
let fruits = ["a", "b", "c", "d"];
let n = fruits.shift()
console.log(n); // 'a'
console.log(fruits); // ['b', 'c', 'd']
(4) unshift()
向数组的开头添加一个或更多元素,并返回新的长度
array.unshift(item1,item2, ..., itemX)
- 该方法将改变数组的数目
let fruits = ["a", "b", "c", "d"];
let n = fruits.unshift()
let m = fruits.unshift('m', 'n')
console.log(n); // 4
console.log(m); // 6
console.log(fruits); // ['m', 'n', 'a', 'b', 'c', 'd']
(5) 💥splice()
从数组中添加或删除元素
array.splice(index,howmany,item1,.....,itemX)
-
index: 必需。规定从何处添加/删除元素。
-
howmany: 可选。规定应该删除多少元素。必须是数字,但可以是 "0"。
-
item: 可选。要添加到数组的新元素
-
这种方法会改变原始数组
-
如果删除元素,则返回含有被删除的元素的数组。 如果未删除任何元素,则返回空数组
let fruits = ["a", "b", "c", "d"];
let n = fruits.splice(1, 0)
console.log(n); // []
console.log(fruits); // ['a', 'b', 'c', 'd']
let m = fruits.splice(1, 0, 'm', 'n')
console.log(m); // []
console.log(fruits); // ['a', 'm', 'n', 'b', 'c', 'd']
let p = fruits.splice(2, 1)
console.log(p); // ['n']
console.log(fruits); // ['a', 'm', 'b', 'c', 'd']
let q = fruits.splice(2, 1, 'k')
console.log(q); // ['b']
console.log(fruits); // ['a', 'm', 'k', 'c', 'd']
(6) 💥slice()
数组截取slice(begin,end),返回被截取项目的新数组
- slice() 方法不会改变原始数组
let arr = ['a', 'b', 'c', 1, 2]
let arr1 = arr.slice() // ['a', 'b', 'c', 1, 2]
let arr2 = arr.slice(1, 3) // ['b', 'c']
let arr3 = arr.slice(-3, -1) // ['c', 1]
let arr4 = arr.slice(-3) // ['c', 1, 2]
2. 拼接数组
concat()
连接两个或多个数组
array1.concat(array2,array3,...,arrayX)
-
不会改变现有的数组
-
返回被连接数组的一个副本
-
如果要进行 concat() 操作的参数是数组,那么添加的是数组中的元素,而不是数组
let hege = ["Cecilie", "Lone"];
let stale = ["Emil", "Tobias", "Linus"];
let kai = ["Robin"];
let children = hege.concat(stale, kai)
// ['Cecilie', 'Lone', 'Emil', 'Tobias', 'Linus', 'Robin']
✔一道面试题:传递两个参数m,n,返回长度为m,所有元素都为n的数组,要求不能用循环。 利用函数的递归和 concat() 方法可以实现,代码如下:
function fn(m, n) {
let arr = []
return m ? fn(m - 1, n).concat(n) : []
}
console.log(fn(3, 1)); // [1, 1, 1]
3. 检测是否为数组
(1) instanceof
instanceof 运算符,可以判断一个对象是否属于哪种类型
let arr = [1,2]
let obj = {'tom'}
arr instanceof Array // true
obj instanceof Array // false
obj instanceof Object // true
(2) Array.isArray()
判断对象是否为数组
如果对象是数组返回 true,否则返回 false
Array.isArray(obj)
let arr = [1,2]
let obj = {'tom'}
Array.isArray(arr) // true
Array.isArray(obj) // false
4. 数组排序
(1) sort()
对数组的元素进行排序
-
排序顺序可以是字母或数字,并按升序或降序。
-
默认排序顺序为按字母升序。
-
这种方法会改变原始数组
-
返回新数组
// 数字排序(数字和升序)
let points = [40,100,1,5,25,10];
points.sort(function(a,b){return a-b});
// [1,5,10,25,40,100]
// 数字排序(数字和降序)
let points = [40,100,1,5,25,10];
points.sort(function(a,b){return b-a});
// [100,40,25,10,5,1]
// 字母排序
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
// Apple,Banana,Mango,Orange
(2) reverse()
反转数组的元素顺序
-
这种方法会改变原始数组
-
返回新数组
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.reverse();
// [Mango,Apple,Orange,Banana]
5. 数组索引方法
(1) indexOf()
如果找到一个 item,则返回 item 的第一次出现的位置。
array.indexOf(item,start)
- 返回元素在数组中第一次出现的位置,如果没有搜索到则返回 -1
let fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
let a = fruits.indexOf("Apple",4); // 4
(2) lastIndexOf()
如果找到一个 item,则返回 item 的最后一次出现的位置。
array.lastIndexOf(item,start)
- 返回元素在数组中最后一次出现的位置,如果没有搜索到则返回 -1
let fruits=["Banana","Orange","Apple","Mango","Banana","Orange","Apple"];
let a = fruits.lastIndexOf("Apple"); // 6
let b = fruits.lastIndexOf("Apple",4); // 2
6. 数组转换为字符串
(1) toString()
把数组转换为字符串,并返回结果
注意: 数组中的元素之间用逗号分隔
let arr = ['a', 'b', 'c', 1, 2]
let str = arr.toString() // a,b,c,1,2
(2) join()
把数组的所有元素放入一个字符串
array.join(separator)
-
元素是通过指定的分隔符进行分隔的
-
separator: 可选。指定要使用的分隔符。如果省略该参数,则使用逗号作为分隔符。
-
返回字符串
let arr = ['a', 'b', 'c', 1, 2]
let str1 = arr.join() // a,b,c,1,2
let str2 = arr.join('-') // a-b-c-1-2
7. 💥迭代(遍历)方法
(1) every()
检测数组所有元素是否都符合指定条件(通过函数提供)
array.every(function(currentValue,index,arr), thisValue)
| 参数 | 描述 |
|---|---|
| currentValue | 必须。当前元素的值 |
| index | 可选。当前元素的索引值 |
| arr | 可选。当前元素属于的数组对象 |
使用指定函数检测数组中的所有元素:
-
如果数组中检测到有一个元素不满足,则整个表达式返回 false ,且剩余的元素不会再进行检测。
-
如果所有元素都满足条件,则返回 true。
-
如果省略了 thisValue ,"this" 的值为 "undefined"
注意: every() 不会对空数组进行检测。
注意: every() 不会改变原始数组。
const values = [1, 3, 4, 6, 7, 4, 3, 1];
const everyResult = values.every((item, index, array) => {
return item > 2;
});
console.log(everyResult); // false
(2) some()
检测数组中的元素是否满足指定条件(函数提供)。
some() 方法会依次执行数组的每个元素:
- 如果有一个元素满足条件,则表达式返回true , 剩余的元素不会再执行检测。
- 如果没有满足条件的元素,则返回false。
注意: some() 不会对空数组进行检测。
注意: some() 不会改变原始数组。
const someResult = values.some((item, index, array) => {
return item > 2;
});
console.log(someResult); // true
(3) filter()
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
注意: filter() 不会对空数组进行检测。
注意: filter() 不会改变原始数组。
const values = [1, 3, 4, 6, 7, 4, 3, 1];
const filterResult = values.filter((item, index, array) => {
return item > 2;
});
console.log(filterResult); // [ 3, 4, 6, 7, 4, 3 ]
const obj = [ { num: 3 }, { num: 4 }, { num: 1 },{ num: 5 },{ num: 0 }, { num: 4 }];
const filterObjResult = obj.filter((item, index, array) => {
return item.num > 2;
});
console.log(filterObjResult); // [ { num: 3 }, { num: 4 }, { num: 5 }, { num: 4 } ]
(4) forEach()
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
注意: forEach() 对于空数组是不会执行回调函数的。
const values = [1, 3, 4, 6, 7, 4, 3, 1];
values.forEach((item, index, array) => {
array[index] = item * 2;
});
console.log(values); // [ 2, 6, 8, 12, 14, 8, 6, 2 ]
(5) map()
map() 方法返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
map() 方法按照原始数组元素顺序依次处理元素。
注意: map() 不会对空数组进行检测。
注意: map() 不会改变原始数组。
const values = [1, 3, 4, 6, 7, 4, 3, 1];
const mapResult = values.map((item, index, array) => {
return item * 2;
});
console.log(mapResult); // [ 2, 6, 8, 12, 14, 8, 6, 2 ]
const obj = [ { num: 3 }, { num: 4 }, { num: 1 },{ num: 5 },{ num: 0 }, { num: 4 }];
const mapObjResult = obj.map((item, index, array) => {
return item.num;
});
console.log(mapObjResult); // [ 3, 4, 1, 5, 0, 4 ]
(6) reduce() & reduceRight()
reduce()将数组元素计算为一个值(从左到右)
reduceRight()将数组元素计算为一个值(从右到左)。
reduce() 方法接收一个函数作为累加器,数组中的每个值(从左到右)开始缩减,最终计算为一个值。
reduce() 可以作为一个高阶函数,用于函数的 compose。
注意: reduce() 对于空数组是不会执行回调函数的。
array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
| 参数 | 描述 |
|---|---|
| total | 必需。初始值, 或者计算结束后的返回值。 |
| currentValue | 必需。当前元素 |
| currentIndex | 可选。当前元素的索引 |
| arr | 可选。当前元素所属的数组对象。 |
const values = [1, 3, 4, 4, 4, 9];
const sum = values.reduce((prev, cur, index, array) => {
return prev + cur;
});
console.log(sum); // 25
const sumRight = values.reduceRight((prev, cur, index, array) => {
return prev + cur;
});
console.log(sumRight); // 25
8. ES6
(1) 扩展运算符...
... 扩展运算符能将数组转换为逗号分隔的参数序列。(展开语法)
const colors = ['green', 'red', 'pink'];
const colors1 = ['white', 'grey'];
const colors2 = [...colors, ...colors1];
console.log(colors2); // [ 'green', 'red', 'pink', 'white', 'grey' ]
(2) find() & findIndex()
find()用于找出第一个符合条件的数组成员,如果没有找到返回undefined findIndex()用于找出第一个符合条件的数组成员的位置,如果没有找到返回*-1*
find() 方法为数组中的每个元素都调用一次函数执行:
- 当数组中的元素在测试条件时返回 true 时, find() 返回符合条件的元素,之后的值不会再调用执行函数。
- 如果没有符合条件的元素返回 undefined
注意: find() 对于空数组,函数是不会执行的。
注意: find() 并没有改变数组的原始值。
const values = [1, 3, 4, 5, 6, NaN];
const findResult = values.find(num => num > 4 ); // 找不到为undefined
console.log(findResult); // 5
const findIndexResult = values.findIndex(num => num > 4 ); // 找不到为-1
console.log(findIndexResult); // 3
(3) Array.from() & Array.of()
Array.from(object, mapFunction, thisValue)
-
Array.from() 方法用于通过拥有 length 属性的对象或可迭代的对象来返回一个数组。如果对象是数组返回 true,否则返回 false
-
Array.of()将参数中所有值作为元素形成数组。
const obj = {
'0': '123',
'1': '456',
'2': 'c',
length: 4
}
const arr = Array.from(obj);
console.log(arr); // [ '123', '456', 'c', undefined ]
const values = [1, 1, 3, 5];
const setValue = new Set(values);
const newArr = Array.from(setValue); // 也可以直接[...new Set(values)]
console.log(newArr); // [ 1, 3, 5 ]
const newArr2 = Array.from(newArr, x => x * 2);
console.log(newArr2); // [ 2, 6, 10 ]
console.log(Array.of(undefined, 1, null)); // [ undefined, 1, null ]
(4) copyWithin()
用于从数组的指定位置拷贝元素到数组的另一个指定位置中
array.copyWithin(target, start, end)
| 参数 | 描述 |
|---|---|
| target | 必需。复制到指定目标索引位置。 |
| start | 可选。元素复制的起始位置。 |
| end | 可选。停止复制的索引位置 (默认为 array.length)。如果为负值,表示倒数。 |
const arr = [1, 3, 4, 4, 5, 8, 10, 1, 0].copyWithin(0, 3, 4);
console.log(arr); // [ 4, 3, 4, 4, 5, 8, 10, 1, 0 ]
const arr = [1, 3, 4, 4, 5, 8, 10, 1, 0].copyWithin(0, 3, 8);
console.log(arr1); // [ 4, 5, 8, 10, 1, 8, 10, 1, 0 ]
(5) fill()
fill() 方法用于将一个固定值替换数组的元素
// 参数1:用来填充的值
// 参数2:被填充的起始索引
// 参数3(可选):被填充的结束索引,默认为数组末尾
const colors = ['green', 'red', 'pink'];
const colors1 = colors.fill('white');
const colors2 = colors.fill('white', 1, 3);
console.log(colors1); // [ 'white', 'white', 'white' ]
console.log(colors2); // [ 'green', 'white', 'white' ]
(6) entries() & keys() & values()
-
entries()返回一个数组的迭代对象,该对象包含数组的键值对 (key/value)。迭代对象中数组的索引值作为 key, 数组元素作为 value。
-
keys() 方法用于从数组创建一个包含数组键的可迭代对象。如果对象是数组返回 true,否则返回 false。
-
values() 方法用于从数组创建一个包含数组值的可迭代对象。如果对象是数组返回 true,否则返回 false。
const colors = ["red", "green", "blue"];
for (const index of colors.keys()) {
console.log(index); // 0 1 2
}
for (const ele of colors.values()) {
console.log(ele); // red green blue
}
for (const [index, ele] of colors.entries()) {
console.log(index, ele);
}
// 0 red
// 1 green
// 2 blue
ES7
includes()
判断一个数组是否包含一个指定的值,如果是返回 true,否则false
arr.includes(searchElement, fromIndex)
[1, 2, 3].includes(2); // true
[1, 2, 3].includes(4); // false
[1, 2, 3].includes(3, 3); // false
[1, 2, 3].includes(3, -1); // true
[1, 2, NaN].includes(NaN); // true
ES10
flat() & flatMap()
嵌套数组转一维数组
console.log([1 ,[2, 3]].flat()); // [1, 2, 3]
// 指定转换的嵌套层数
console.log([1, [2, [3, [4, 5]]]].flat(2)); // [1, 2, 3, [4, 5]]
// 不管嵌套多少层
console.log([1, [2, [3, [4, 5]]]].flat(Infinity)); // [1, 2, 3, 4, 5]
// 自动跳过空位
console.log([1, [2, , 3]].flat());<p> // [1, 2, 3]
// 先对数组中每个元素进行了的处理,再对数组执行 flat() 方法。
// 参数1:遍历函数,该遍历函数可接受3个参数:当前元素、当前元素索引、原数组
// 参数2:指定遍历函数中 this 的指向
console.log([1, 2, 3].flatMap(n => [n * 2])); // [2, 4, 6]