先放一个语雀的链接:
https://www.yuque.com/docs/share/13314a2f-05c0-4de6-8d61-8acd9e566ad4?# 《JS内置对象 Array》
1. at()接收一个整数值并返回该索引对应的元素
at() 方法接收一个整数值并返回该索引对应的元素,允许正数和负数。负整数从数组中的最后一个元素开始倒数。
at() 方法是通用的。其仅期望 this 具有 length 属性和以整数为键的属性。
const array1 = [5, 12, 8, 130, 44]; let index = 2; console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`); // expected output: "Using an index of 2 the item returned is 8" index = -2; console.log(`Using an index of ${index} item returned is ${array1.at(index)}`); // expected output: "Using an index of -2 item returned is 130"
- 返回数组的最后一个值:
// 数组及数组元素 const cart = ['apple', 'banana', 'pear']; // 一个函数,用于返回给定数组的最后一个元素 function returnLast(arr) { return arr.at(-1); } // 获取 'cart' 数组的最后一个元素 const item1 = returnLast(cart); console.log(item1); // 输出:'pear' // 在 'cart' 数组中添加一个元素 cart.push('orange'); const item2 = returnLast(cart); console.log(item2); // 输出:'orange'
- 比较不同的数组方法
这个示例比较了选择 Array 中倒数第二个元素的不同方法。凸显了 at() 方法的简洁性和可读性。
// 数组及数组元素 const colors = ['red', 'green', 'blue']; // 使用长度属性 const lengthWay = colors[colors.length-2]; console.log(lengthWay); // 输出:'green' // 使用 slice() 方法。注意会返回一个数组 const sliceWay = colors.slice(-2, -1); console.log(sliceWay[0]); // 输出:'green' // 使用 at() 方法 const atWay = colors.at(-2); console.log(atWay); // 输出:'green'
- 在非数组对象上调用 at( )
-
- at() 方法读取 this 的 length 属性并计算需要访问的索引。
const arrayLike = { length: 2, 0: "a", 1: "b", }; console.log(Array.prototype.at.call(arrayLike, -1)); // "b"
2. concat()合并两个或多个数组
concat() 方法用于合并两个或多个数组。此方法不会更改现有数组,而是返回一个新数组。
举例: const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // expected output: Array ["a", "b", "c", "d", "e", "f"] 语法: concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) 参数 valueN 可选 数组和/或值,将被合并到一个新的数组中。如果省略了所有 valueN 参数, 则 concat 会返回调用此方法的现存数组的一个浅拷贝。
- 合并嵌套数组:
const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // 修改 num1 的第一个元素 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]]
3.copyWithin( ) 浅复制数组的一部分到同一数组中的另一个位置,并返回它
copyWithin() 方法浅复制数组的一部分到同一数组中的另一个位置,并返回它,不会改变原数组的长度。copyWithin 函数被设计为通用式的,其不要求其 this 值必须是一个数组对象。
const array1 = ['a', 'b', 'c', 'd', 'e']; // copy to index 0 the element at index 3 console.log(array1.copyWithin(0, 3, 4)); // expected output: Array ["d", "b", "c", "d", "e"] // copy to index 1 all elements from index 3 to the end console.log(array1.copyWithin(1, 3)); // expected output: Array ["d", "d", "e", "d", "e"]
- 语法:
copyWithin(target)
copyWithin(target, start)
copyWithin(target, start, end)
- 参数
target
0 为基底的索引,复制序列到该位置。如果是负数,target 将从末尾开始计算。如果 target 大于等于 arr.length,将不会发生拷贝。如果 target 在 start 之后,复制的序列将被修改以符合 arr.length。
start
0 为基底的索引,开始复制元素的起始位置。如果是负数,start 将从末尾开始计算。如果 start 被忽略,copyWithin 将会从 0 开始复制。
end
0 为基底的索引,开始复制元素的结束位置。copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。如果是负数, end 将从末尾开始计算。如果 end 被忽略,copyWithin 方法将会一直复制至数组结尾(默认为 arr.length)
- 返回值: 改变后的数组。
- 示例:
[1, 2, 3, 4, 5].copyWithin(-2) // [1, 2, 3, 1, 2] //从-2的位置开始复制,复制的对象为原数组 [1, 2, 3, 4, 5].copyWithin(0, 3) // [4, 5, 3, 4, 5] //从0的位置开始复制,将下标为3的值复制到下标为0的地方 [1, 2, 3, 4, 5].copyWithin(0, 3, 4) // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(-2, -3, -1) // [1, 2, 3, 3, 4] [].copyWithin.call({length: 5, 3: 1}, 0, 3); // {0: 1, 3: 1, length: 5} // ES2015 Typed Arrays are subclasses of Array var i32a = new Int32Array([1, 2, 3, 4, 5]); i32a.copyWithin(0, 2); // Int32Array [3, 4, 5, 4, 5] // On platforms that are not yet ES2015 compliant: [].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4); // Int32Array [4, 2, 3, 4, 5]
4. entries( ) 返回一个新的数组迭代器对象
entries() 方法返回一个新的数组迭代器对象,该对象包含数组中每个索引的键/值对。
const array1 = ['a', 'b', 'c']; const iterator1 = array1.entries(); console.log(iterator1.next().value); // expected output: Array [0, "a"] console.log(iterator1.next().value); // expected output: Array [1, "b"]
- 迭代索引和元素
const a = ["a", "b", "c"]; for (const [index, element] of a.entries()) { console.log(index, element); } // 0 'a' // 1 'b' // 2 'c'
- 使用 for ... of循环
const array = ["a", "b", "c"]; const arrayEntries = array.entries(); for (const element of arrayEntries) { console.log(element); } // [0, 'a'] // [1, 'b'] // [2, 'c']
- 在非数组对象上调用 entries ()
entries() 方法读取 this 的 length 属性,然后访问每个整数索引。
const arrayLike = { length: 3, 0: "a", 1: "b", 2: "c", }; for (const entry of Array.prototype.entries.call(arrayLike)) { console.log(entry); } // [ 0, 'a' ] // [ 1, 'b' ] // [ 2, 'c' ]
5. every () 测试一个数组内的所有元素是否都能通过某个指定函数的测试。
every() 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。若收到一个空数组,此方法在任何情况下都会返回 true。
const isBelowThreshold = (currentValue) => currentValue < 40; const array1 = [1, 30, 39, 29, 10, 13]; console.log(array1.every(isBelowThreshold)); // expected output: true
- 语法
// 箭头函数 every((element) => { /* … */ } ) every((element, index) => { /* … */ } ) every((element, index, array) => { /* … */ } ) // 回调函数 every(callbackFn) every(callbackFn, thisArg) // 内联回调函数 every(function(element) { /* … */ }) every(function(element, index) { /* … */ }) every(function(element, index, array){ /* … */ }) every(function(element, index, array) { /* … */ }, thisArg) 参数: callback 用来测试每个元素的函数,它可以接收三个参数: element 用于测试的当前值。 index 用于测试的当前值的索引。 array 调用 every 的当前数组。
- 示例:检测所有数组元素的大小
下例检测数组中的所有元素是否都大于 10。 function isBigEnough(element, index, array) { return element >= 10; } [12, 5, 8, 130, 44].every(isBigEnough); // false [12, 54, 18, 130, 44].every(isBigEnough); // true 箭头函数为上面的检测过程提供了更简短的语法。 [12, 5, 8, 130, 44].every(x => x >= 10); // false [12, 54, 18, 130, 44].every(x => x >= 10); // true
6. fill () 用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。
fill() 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。fill 方法故意被设计成通用方法,该方法不要求 this 是数组对象。当一个对象被传递给 fill 方法的时候,填充数组的是这个对象的引用。
const array1 = [1, 2, 3, 4]; // fill with 0 from position 2 until position 4 console.log(array1.fill(0, 2, 4)); // expected output: [1, 2, 0, 0] // fill with 5 from position 1 console.log(array1.fill(5, 1)); // expected output: [1, 5, 5, 5] console.log(array1.fill(6)); // expected output: [6, 6, 6, 6] 语法: fill(value) fill(value, start) fill(value, start, end) 参数: value 用来填充数组元素的值。 start 可选 起始索引,默认值为 0。 end 可选 终止索引,默认值为 arr.length。 返回值: 修改后的数组。
- 示例:
[1, 2, 3].fill(4); // [4, 4, 4] [1, 2, 3].fill(4, 1); // [1, 4, 4] [1, 2, 3].fill(4, 1, 2); // [1, 4, 3] [1, 2, 3].fill(4, 1, 1); // [1, 2, 3] [1, 2, 3].fill(4, 3, 3); // [1, 2, 3] [1, 2, 3].fill(4, -3, -2); // [4, 2, 3] [1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3] [1, 2, 3].fill(4, 3, 5); // [1, 2, 3] Array(3).fill(4); // [4, 4, 4] [].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3} // Objects by reference. const arr = Array(3).fill({}) // [{}, {}, {}]; // 需要注意如果 fill 的参数为引用类型,会导致都执行同一个引用类型 // 如 arr[0] === arr[1] 为 true arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]
7. filter () 创建给定数组一部分的浅拷贝,过滤数组。
filter() 方法创建给定数组一部分的浅拷贝,其包含通过所提供函数实现的测试的所有元素。filter() 不会改变原数组,而是返回一个新数组。
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; const result = words.filter(word => word.length > 6); console.log(result); // expected output: Array ["exuberant", "destruction", "present"]
- 语法:
// 箭头函数 filter((element) => { /* … */ } ) filter((element, index) => { /* … */ } ) filter((element, index, array) => { /* … */ } ) // 回调函数 filter(callbackFn) filter(callbackFn, thisArg) // 内联回调函数 filter(function(element) { /* … */ }) filter(function(element, index) { /* … */ }) filter(function(element, index, array){ /* … */ }) filter(function(element, index, array) { /* … */ }, thisArg) 参数: callbackFn 用来测试数组中每个元素的函数。返回 true 表示该元素通过测试,保留该元素,false 则不保留。它接受以下三个参数: element 数组中当前正在处理的元素。 index 正在处理的元素在数组中的索引。 array 调用了 filter() 的数组本身。 返回值: 一个新的、由通过测试的元素组成的数组, 如果没有任何数组元素通过测试,则返回空数组。
示例
- 筛选排除所有较小的值
使用 filter() 创建了一个新数组,该数组的元素由原数组中值大于 10 的元素组成。
function isBigEnough(value) { return value >= 10; } const filtered = [12, 5, 8, 130, 44].filter(isBigEnough); // filtered is [12, 130, 44]
- 找出数组中所有的素数
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]; function isPrime(num) { for (let i = 2; num > i; i++) { if (num % i === 0) { return false; } } return num > 1; } console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
- 过滤 JSON 中的无效条目
-
- 使用 filter() 创建具有非零 id 的元素的 json。
const arr = [ { id: 15 }, { id: -1 }, { id: 0 }, { id: 3 }, { id: 12.2 }, {}, { id: null }, { id: NaN }, { id: 'undefined' }, ]; let invalidEntries = 0; function filterByID(item) { if (Number.isFinite(item.id) && item.id !== 0) { return true; } invalidEntries++; return false; } const arrByID = arr.filter(filterByID); console.log('Filtered Array\n', arrByID); // 过滤后的数组 // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }] console.log('Number of Invalid Entries = ', invalidEntries); // Number of Invalid Entries = 5
- 在数组中搜索
-
- 使用 filter() 根据搜索条件来过滤数组内容。
const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange']; /** * 根据搜索条件(查询)筛选数组项 */ function filterItems(arr, query) { return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase())); } console.log(filterItems(fruits, 'ap')); // ['apple', 'grapes'] console.log(filterItems(fruits, 'an')); // ['banana', 'mango', 'orange']
8. find () 返回数组中满足提供的测试函数的第一个元素的值。
find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。find 方法不会改变数组。
const array1 = [5, 12, 8, 130, 44]; const found = array1.find(element => element > 10); console.log(found); // expected output: 12
- 如果需要在数组中找到对应元素的索引,请使用 findIndex()。
- 如果需要查找某个值的索引,请使用 Array.prototype.indexOf()。(它类似于 Array.prototype.indexOf(),但只是检查每个元素是否与值相等,而不是使用测试函数。)
- 如果需要查找数组中是否存在值,请使用 Array.prototype.includes()。同样,它检查每个元素是否与值相等,而不是使用测试函数。
- 如果需要查找是否有元素满足所提供的测试函数,请使用 Array.prototype.some()。
语法:
// 箭头函数 find((element) => { /* … */ } ) find((element, index) => { /* … */ } ) find((element, index, array) => { /* … */ } ) // 回调函数 find(callbackFn) find(callbackFn, thisArg) // 内联回调函数 find(function(element) { /* … */ }) find(function(element, index) { /* … */ }) find(function(element, index, array){ /* … */ }) find(function(element, index, array) { /* … */ }, thisArg) 参数: callbackFn 在数组每一项上执行的函数,接收 3 个参数: element 当前遍历到的元素。 index 当前遍历到的索引。 array 数组本身。 返回值: 数组中第一个满足所提供测试函数的元素的值,否则返回 undefined。
示例:
- 用对象属性查找数组里的对象
const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.find(isCherries)); // { name: 'cherries', quantity: 5 }
- 使用箭头函数和解构赋值
const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; const result = inventory.find(({ name }) => name === 'cherries'); console.log(result) // { name: 'cherries', quantity: 5 } //不带花括号
- 寻找数组中的第一个质数
-
- 如何从数组中寻找质数(如果找不到质数则返回 undefined)
function isPrime(element, index, array) { let start = 2; while (start <= Math.sqrt(element)) { if (element % start++ < 1) { return false; } } return element > 1; } console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found console.log([4, 5, 8, 12].find(isPrime)); // 5
9. findIndex () 数组中满足提供的测试函数的第一个元素的索引。
findIndex()方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回 -1。
const array1 = [5, 12, 8, 130, 44]; const isLargeNumber = (element) => element > 13; console.log(array1.findIndex(isLargeNumber)); // expected output: 3
10. findLast ()数组中满足提供的测试函数条件的最后一个元素的值。
findLast() 方法返回数组中满足提供的测试函数条件的最后一个元素的值。如果没有找到对应元素,则返回 undefined。
const array1 = [5, 12, 50, 130, 44]; const found = array1.findLast((element) => element > 45); console.log(found); // expected output: 130
11. findLastIndex () 数组中满足提供的测试函数的最后一个元素的索引。
findLastIndex() 方法返回数组中满足提供的测试函数条件的最后一个元素的索引。若没有找到对应元素,则返回 -1。
const array1 = [5, 12, 50, 130, 44]; const isLargeNumber = (element) => element > 45; console.log(array1.findLastIndex(isLargeNumber)); // expected output: 3 (of element with value: 130)
12. flat()按照一个可指定的深度递归遍历数组,并返回新数组。
flat() 方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。
const arr1 = [0, 1, 2, [3, 4]]; console.log(arr1.flat()); // expected output: [0, 1, 2, 3, 4] const arr2 = [0, 1, 2, [[[3, 4]]]]; console.log(arr2.flat(2)); // expected output: [0, 1, 2, [3, 4]]
语法:
flat() flat(depth) 参数: depth 可选 指定要提取嵌套数组的结构深度,默认值为 1。 返回值: 一个包含将数组与子数组中所有元素的新数组。
示例:
- 扁平化嵌套数组
使用 flat(Infinity)
,可展开任意深度的嵌套数组
var arr1 = [1, 2, [3, 4]]; arr1.flat(); // [1, 2, 3, 4] var arr2 = [1, 2, [3, 4, [5, 6]]]; arr2.flat(); // [1, 2, 3, 4, [5, 6]] var arr3 = [1, 2, [3, 4, [5, 6]]]; arr3.flat(2); // [1, 2, 3, 4, 5, 6] //使用 Infinity,可展开任意深度的嵌套数组 var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; arr4.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
- 扁平化与数组空项
flat() 方法会移除数组中的空项:
var arr4 = [1, 2, , 4, 5]; arr4.flat(); // [1, 2, 4, 5]
13. flatMap () 使用映射函数映射每个元素,然后将结果压缩成一个新数组。
flatMap() 方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。它与 map 连着深度值为 1 的 flat 几乎相同,但 flatMap 通常在合并成一种方法的效率稍微高一些。
const arr1 = [1, 2, [3], [4, 5], 6, []]; const flattened = arr1.flatMap(num => num); console.log(flattened); // expected output: Array [1, 2, 3, 4, 5, 6]
示例:
- map( ) 与 flatMap( )
var arr1 = [1, 2, 3, 4]; arr1.map(x => [x * 2]); // [[2], [4], [6], [8]] arr1.flatMap(x => [x * 2]); // [2, 4, 6, 8] // only one level is flattened arr1.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]]
14. forEach () 对数组的每个元素执行一次给定的函数。
forEach() 方法对数组的每个元素执行一次给定的函数。
const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // expected output: "a" // expected output: "b" // expected output: "c"
备注: 除了抛出异常以外,没有办法中止或跳出 forEach() 循环。如果你需要中止或跳出循环,forEach() 方法不是应当使用的工具。
若你需要提前终止循环,你可以使用:
- 一个简单的 for 循环
- for...of / for...in 循环
- Array.prototype.every()
- Array.prototype.some()
- Array.prototype.find()
- Array.prototype.findIndex()
这些数组方法则可以对数组元素判断,以便确定是否需要继续遍历:
译者注:只要条件允许,也可以使用 filter() 提前过滤出需要遍历的部分,再用 forEach() 处理。
示例:
- 不对未初始化的值做任何操作(稀疏数组)
const arraySparse = [1, 3, /* empty */, 7]; let numCallbackRuns = 0; arraySparse.forEach((element) => { console.log({ element }); numCallbackRuns++; }); console.log({ numCallbackRuns }); // { element: 1 } // { element: 3 } // { element: 7 } // { numCallbackRuns: 3 } 如图,3 到 7 之间的缺失值没有调用回调函数。
- 将 for 循环转换为 forEach
const items = ['item1', 'item2', 'item3']; const copyItems = []; // before for (let i = 0; i < items.length; i++) { copyItems.push(items[i]); } // after items.forEach((item) => { copyItems.push(item); });
- 扁平化数组
const flatten = (arr) => { const result = []; arr.forEach((item) => { if (Array.isArray(item)) { result.push(...flatten(item)); } else { result.push(item); } }); return result; } // 使用 const nested = [1, 2, 3, [4, 5, [6, 7], 8, 9]]; console.log(flatten(nested)); // [1, 2, 3, 4, 5, 6, 7, 8, 9]
15. from () 对一个类似数组或可迭代对象创建一个新的,浅拷贝的数组实例。 把非数组->数组。
console.log(Array.from('foo')); // expected output: Array ["f", "o", "o"] console.log(Array.from([1, 2, 3], x => x + x)); // expected output: Array [2, 4, 6]
语法:
// 箭头函数 Array.from(arrayLike, (element) => { /* … */ } ) Array.from(arrayLike, (element, index) => { /* … */ } ) // 映射函数 Array.from(arrayLike, mapFn) Array.from(arrayLike, mapFn, thisArg) // 内联映射函数 Array.from(arrayLike, function mapFn(element) { /* … */ }) Array.from(arrayLike, function mapFn(element, index) { /* … */ }) Array.from(arrayLike, function mapFn(element) { /* … */ }, thisArg) Array.from(arrayLike, function mapFn(element, index) { /* … */ }, thisArg) 参数: arrayLike 想要转换成数组的伪数组对象或可迭代对象。 mapFn 可选 如果指定了该参数,新数组中的每个元素会执行该回调函数。 thisArg 可选 可选参数,执行回调函数 mapFn 时 this 对象。 返回值: 一个新的数组实例。
示例:
- 从
String
生成数组
Array.from('foo'); // [ "f", "o", "o" ]
- 从
Set
生成数组
const set = new Set(['foo', 'bar', 'baz', 'foo']); Array.from(set); // [ "foo", "bar", "baz" ]
- 从
Map
生成数组
const map = new Map([[1, 2], [2, 4], [4, 8]]); Array.from(map); // [[1, 2], [2, 4], [4, 8]] const mapper = new Map([['1', 'a'], ['2', 'b']]); Array.from(mapper.values()); // ['a', 'b']; Array.from(mapper.keys()); // ['1', '2'];
- 从类数组对象(arguments)生成数组
function f() { return Array.from(arguments); } f(1, 2, 3); // [ 1, 2, 3 ]
- 数组合并去重
function combine(){ let arr = [].concat.apply([], arguments); //没有去重复的新数组 return Array.from(new Set(arr)); } var m = [1, 2, 2], n = [2,3,3]; console.log(combine(m,n)); // [1, 2, 3]
16. includes() 判断一个数组是否包含一个指定的值。
includes() 方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回 false。使用 includes() 比较字符串和字符时是区分大小写的。
const array1 = [1, 2, 3]; console.log(array1.includes(2)); // expected output: true const pets = ['cat', 'dog', 'bat']; console.log(pets.includes('cat')); // expected output: true console.log(pets.includes('at')); // expected output: false
语法:
includes(searchElement) includes(searchElement, fromIndex) 参数: searchElement 需要查找的元素值。 fromIndex 可选 从fromIndex 索引处开始查找 searchElement。 如果为负值,则按升序从 array.length + fromIndex 的索引开始搜 (即使从末尾开始往前跳 fromIndex 的绝对值个索引,然后往后搜寻)。默认为 0。
示例:
[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
- 如果 fromIndex 大于等于数组的长度,则将直接返回 false,且不搜索该数组。
var arr = ['a', 'b', 'c']; arr.includes('c', 3); // false arr.includes('c', 100); // false
- 计算出的索引小于 0
-
- 如果 fromIndex 为负值,计算出的索引将作为开始搜索 searchElement 的位置。如果计算出的索引小于 0,则整个数组都会被搜索。
// array length is 3 // fromIndex is -100 // computed index is 3 + (-100) = -97 var arr = ['a', 'b', 'c']; arr.includes('a', -100); // true arr.includes('b', -100); // true arr.includes('c', -100); // true arr.includes('a', -2); // false
- 作为通用方法的 Includes ( )
-
- includes() 方法有意设计为通用方法。它不要求this值是数组对象,所以它可以被用于其他类型的对象 (比如类数组对象)。下面的例子展示了 在函数的 arguments 对象上调用的 includes() 方法。
(function() { console.log([].includes.call(arguments, 'a')); // true console.log([].includes.call(arguments, 'd')); // false })('a','b','c');
17. indexOf() 返回在数组中可以找到给定元素的第一个索引。
indexOf() 方法返回在数组中可以找到给定元素的第一个索引,如果不存在,则返回 -1。
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // expected output: 1 // start from index 2 console.log(beasts.indexOf('bison', 2)); // expected output: 4 console.log(beasts.indexOf('giraffe')); // expected output: -1
语法:
indexOf(searchElement) indexOf(searchElement, fromIndex) 参数: searchElement 要查找的元素。 fromIndex 可选 开始查找的位置。如果该索引值大于或等于数组长度,意味着不会在数组里查找,返回 -1。如果参数中提供的索引值是一个负值,则将其作为数组末尾的一个抵消,即 -1 表示从最后一个元素开始查找,-2 表示从倒数第二个元素开始查找,以此类推。注意:如果参数中提供的索引值是一个负值,并不改变其查找顺序,查找顺序仍然是从前向后查询数组。如果抵消后的索引值仍小于 0,则整个数组都将会被查询。其默认值为 0。 返回值: 首个被找到的元素在数组中的索引位置; 若没有找到则返回 -1。
示例:
- 找出指定元素出现的所有位置
const indices = []; const array = ['a', 'b', 'a', 'c', 'a', 'd']; const element = 'a'; let idx = array.indexOf(element); while (idx !== -1) { indices.push(idx); idx = array.indexOf(element, idx + 1); } console.log(indices); // [0, 2, 4]
- 判断一个元素是否在数组里,不在则更新数组
function updateVegetablesCollection (veggies, veggie) { if (veggies.indexOf(veggie) === -1) { veggies.push(veggie); console.log(`New veggies collection is: ${veggies}`); } else { console.log(`${veggie} already exists in the veggies collection.`); } } const veggies = ['potato', 'tomato', 'chillies', 'green-pepper']; updateVegetablesCollection(veggies, 'spinach'); // New veggies collection is: potato,tomato,chillies,green-pepper,spinach updateVegetablesCollection(veggies, 'spinach'); // spinach already exists in the veggies collection.
18. isArray() 用于确定传递的值是否是一个 Array。
Array.isArray() 用于确定传递的值是否是一个数组。
Array.isArray([1, 2, 3]); // true Array.isArray({foo: 123}); // false Array.isArray('foobar'); // false Array.isArray(undefined); // false
语法:
Array.isArray(value) 参数: value 需要检测的值。 返回值: 如果值是 Array,则为 true;否则为 false。
示例:
// 下面的函数调用都返回 true Array.isArray([]); Array.isArray([1]); Array.isArray(new Array()); Array.isArray(new Array('a', 'b', 'c', 'd')) Array.isArray(new Array(3)); // 鲜为人知的事实:其实 Array.prototype 也是一个数组。 Array.isArray(Array.prototype); // 下面的函数调用都返回 false Array.isArray(); Array.isArray({}); Array.isArray(null); Array.isArray(undefined); Array.isArray(17); Array.isArray('Array'); Array.isArray(true); Array.isArray(false); Array.isArray(new Uint8Array(32)) Array.isArray({ __proto__: Array.prototype });
19. join() 将一个数组的所有元素连接成一个字符串并返回这个字符串。
join() 方法将一个数组(或一个类数组对象)的所有元素连接成一个字符串并返回这个字符串,用逗号或指定的分隔符字符串分隔。如果数组只有一个元素,那么将返回该元素而不使用分隔符。
const elements = ['Fire', 'Air', 'Water']; console.log(elements.join()); // expected output: "Fire,Air,Water" console.log(elements.join('')); // expected output: "FireAirWater" console.log(elements.join('-')); // expected output: "Fire-Air-Water"
语法:
join() join(separator) 参数: separator 可选 指定一个字符串来分隔数组的每个元素。如果需要,将分隔符转换为字符串。如果省略,数组元素用逗号(,)分隔。如果 separator 是空字符串(""),则所有元素之间都没有任何字符。 返回值: 一个所有数组元素连接的字符串。如果 arr.length 为 0,则返回空字符串。
示例:
- 用四种不同的方式连接数组
const a = ['Wind', 'Water', 'Fire']; a.join(); // 'Wind,Water,Fire' a.join(', '); // 'Wind, Water, Fire' a.join(' + '); // 'Wind + Water + Fire' a.join(''); // 'WindWaterFire'
- 在稀疏数组上使用 join()
join() 将空槽视为 undefined,并产生额外的分隔符:
console.log([1, , 3].join()); // '1,,3' console.log([1, undefined, 3].join()); // '1,,3'
- 在非数组对象上调用 join()
const arrayLike = { length: 3, 0: 2, 1: 3, 2: 4, }; console.log(Array.prototype.join.call(arrayLike)); // 2,3,4 console.log(Array.prototype.join.call(arrayLike, ".")); // 2.3.4
20. keys() 返回一个包含数组中每个索引键的 Array Iterator 对象。
keys() 方法返回一个包含数组中每个索引键的 Array Iterator 对象。
const array1 = ['a', 'b', 'c']; const iterator = array1.keys(); for (const key of iterator) { console.log(key); } // expected output: 0 // expected output: 1 // expected output: 2
语法:
语法: keys() 返回值: 一个新的 Array 迭代器对象。
示例:
- 索引迭代器会包含那些没有对应元素的索引
var arr = ["a", , "c"]; var sparseKeys = Object.keys(arr); var denseKeys = [...arr.keys()]; console.log(sparseKeys); // ['0', '2'] console.log(denseKeys); // [0, 1, 2]
21. lastIndexOf() 返回指定元素在数组中的最后一个的索引。
lastIndexOf() 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。
const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']; console.log(animals.lastIndexOf('Dodo')); // expected output: 3 console.log(animals.lastIndexOf('Tiger')); // expected output: 1
示例:
- 查找所有元素:
使用 lastIndexOf 查找到一个元素在数组中所有的索引(下标),并使用 push 将所有添加到另一个数组中。
var indices = []; var array = ['a', 'b', 'a', 'c', 'a', 'd']; var element = 'a'; var idx = array.lastIndexOf(element); while (idx != -1) { indices.push(idx); idx = (idx > 0 ? array.lastIndexOf(element, idx - 1) : -1); } console.log(indices); // [4, 2, 0];
22. map() 遍历之后创建新数组。
map() 方法创建一个新数组,这个新数组由原数组中的每个元素都调用一次提供的函数后的返回值组成。因为 map 生成一个新数组,当你不打算使用返回的新数组却使用 map 是违背设计初衷的,请用 forEach 或者 for-of 替代。
如果有以下情形,则不该使用 map:
- 你不打算使用返回的新数组;或
- 你没有从回调函数中返回值。
const array1 = [1, 4, 9, 16]; // pass a function to map const map1 = array1.map(x => x * 2); console.log(map1); // expected output: Array [2, 8, 18, 32]
示例:
- 求数组中每个元素的平方根。
const numbers = [1, 4, 9]; const roots = numbers.map((item) => Math.sqrt(item)); // roots 现在是 [1, 2, 3] // numbers 依旧是 [1, 4, 9]
- 使用 map 重新格式化数组中的对象。
const kvArray = [ { key: 1, value: 10 }, { key: 2, value: 20 }, { key: 3, value: 30 }, ]; const reformattedArray = kvArray.map(({ key, value}) => ({ [key]: value })); // reformattedArray 现在是 [{1: 10}, {2: 20}, {3: 30}], // kvArray 依然是: // [{key: 1, value: 10}, // {key: 2, value: 20}, // {key: 3, value: 30}]
23. pop() 从数组中删除最后一个元素,并返回该元素的值。
pop() 方法从数组中删除最后一个元素,并返回该元素的值。此方法会更改数组的长度。
const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); // expected output: "tomato" console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); console.log(plants); // expected output: Array ["broccoli", "cauliflower", "cabbage"]
语法:
pop() 返回值: 从数组中删除的元素(当数组为空时返回undefined)。
24. push() 将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
push() 方法将一个或多个元素添加到数组的末尾,并返回该数组的新长度。
const animals = ['pigs', 'goats', 'sheep']; const count = animals.push('cows'); console.log(count); // expected output: 4 console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows"] animals.push('chickens', 'cats', 'dogs'); console.log(animals); // expected output: Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
语法:
push(element0) push(element0, element1) push(element0, element1, /* … ,*/ elementN) 参数: elementN 被添加到数组末尾的元素。 返回值: 当调用该方法时,新的 length 属性值将被返回。
示例:
- 添加元素到数组:
下面的代码创建了 sports 数组,包含两个元素,然后又把两个元素添加给它。total 变量为数组的新长度值。
var sports = ["soccer", "baseball"]; var total = sports.push("football", "swimming"); console.log(sports); // ["soccer", "baseball", "football", "swimming"] console.log(total); // 4
- 合并两个数组
var vegetables = ['parsnip', 'potato']; var moreVegs = ['celery', 'beetroot']; // 将第二个数组融合进第一个数组 // 相当于 vegetables.push('celery', 'beetroot'); Array.prototype.push.apply(vegetables, moreVegs); console.log(vegetables); // ['parsnip', 'potato', 'celery', 'beetroot']
25. reduce() 迭代计算数组所有元素的总和。
reduce() 方法对数组中的每个元素按序执行一个由您提供的 reducer 函数,每一次运行 reducer 会将先前元素的计算结果作为参数传入,最后将其结果汇总为单个返回值。
第一次执行回调函数时,不存在“上一次的计算结果”。如果需要回调函数从数组索引为 0 的元素开始执行,则需要传递初始值。否则,数组索引为 0 的元素将被作为初始值 initialValue,迭代器将从第二个元素开始执行(索引为 1 而不是 0)。
const array1 = [1, 2, 3, 4]; // 0 + 1 + 2 + 3 + 4 const initialValue = 0; const sumWithInitial = array1.reduce( (previousValue, currentValue) => previousValue + currentValue, initialValue ); console.log(sumWithInitial); // expected output: 10
reducer 逐个遍历数组元素,每一步都将当前元素的值与上一步的计算结果相加(上一步的计算结果是当前元素之前所有元素的总和)——直到没有更多的元素被相加。
语法:
// 箭头函数 reduce((previousValue, currentValue) => { /* … */ } ) reduce((previousValue, currentValue, currentIndex) => { /* … */ } ) reduce((previousValue, currentValue, currentIndex, array) => { /* … */ } ) reduce((previousValue, currentValue) => { /* … */ } , initialValue) reduce((previousValue, currentValue, currentIndex) => { /* … */ } , initialValue) reduce((previousValue, currentValue, currentIndex, array) => { /* … */ }, initialValue) // 回调函数 reduce(callbackFn) reduce(callbackFn, initialValue) // 内联回调函数 reduce(function(previousValue, currentValue) { /* … */ }) reduce(function(previousValue, currentValue, currentIndex) { /* … */ }) reduce(function(previousValue, currentValue, currentIndex, array) { /* … */ }) reduce(function(previousValue, currentValue) { /* … */ }, initialValue) reduce(function(previousValue, currentValue, currentIndex) { /* … */ }, initialValue) reduce(function(previousValue, currentValue, currentIndex, array) { /* … */ }, initialValue)
参数:
callbackFn
一个“reducer”函数,包含四个参数:
- previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]。
- currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]。
- currentIndex:数组中正在处理的元素的索引。若指定了初始值 initialValue,则起始索引号为 0,否则从索引 1 起始。
- array:用于遍历的数组。
initialValue 可选
作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。
返回值:
使用“reducer”回调函数遍历整个数组后的结果。
示例:
1. 求数组所有值的和
let sum = [0, 1, 2, 3].reduce(function (previousValue, currentValue) { return previousValue + currentValue }, 0) // sum is 6 你也可以写成箭头函数的形式: let total = [ 0, 1, 2, 3 ].reduce( ( previousValue, currentValue ) => previousValue + currentValue, 0 )
- 将二维数组转化为一维数组
let flattened = [[0, 1], [2, 3], [4, 5]].reduce( function(previousValue, currentValue) { return previousValue.concat(currentValue) }, [] ) // flattened is [0, 1, 2, 3, 4, 5] 你也可以写成箭头函数的形式: let flattened = [[0, 1], [2, 3], [4, 5]].reduce( ( previousValue, currentValue ) => previousValue.concat(currentValue), [] )
- 计算数组中每个元素出现的次数
let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'] let countedNames = names.reduce(function (allNames, name) { if (name in allNames) { allNames[name]++ } else { allNames[name] = 1 } return allNames }, {}) // countedNames is: // { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }
26. reverse() 将数组中元素的位置颠倒,并返回该数组。
reverse() 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。
const array1 = ['one', 'two', 'three']; console.log('array1:', array1); // expected output: "array1:" Array ["one", "two", "three"] const reversed = array1.reverse(); console.log('reversed:', reversed); // expected output: "reversed:" Array ["three", "two", "one"] // Careful: reverse is destructive -- it changes the original array. console.log('array1:', array1); // expected output: "array1:" Array ["three", "two", "one"]
27. shift() 从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
shift() 方法从数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。
示例:
- 移除数组中的一个元素
以下代码显示了删除其第一个元素之前和之后的 myFish 数组。它还显示已删除的元素:
let myFish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('调用 shift 之前:' + myFish); // "调用 shift 之前:angel,clown,mandarin,surgeon" var shifted = myFish.shift(); console.log('调用 shift 之后:' + myFish); // "调用 shift 之后:clown,mandarin,surgeon" console.log('被删除的元素:' + shifted); // "被删除的元素:angel"
28. slice() 返回一个新的数组对象,原始数组不会被改变。
slice() 方法返回一个新的数组对象,这一对象是一个由 begin 和 end 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // expected output: Array ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // expected output: Array ["camel", "duck"] console.log(animals.slice(1, 5)); // expected output: Array ["bison", "camel", "duck", "elephant"] console.log(animals.slice(-2)); // expected output: Array ["duck", "elephant"] console.log(animals.slice(2, -1)); // expected output: Array ["camel", "duck"] console.log(animals.slice()); // expected output: Array ["ant", "bison", "camel", "duck", "elephant"]
语法:
slice() slice(start) slice(start, end) begin 可选: 提取起始处的索引(从 0 开始),从该索引开始提取原数组元素。 如果该参数为负数,则表示从原数组中的倒数第几个元素开始提取, slice(-2) 表示提取原数组中的倒数第二个元素到最后一个元素(包含最后一个元素)。 如果省略 begin,则 slice 从索引 0 开始。 如果 begin 超出原数组的索引范围,则会返回空数组。 end 可选: 提取终止处的索引(从 0 开始),在该索引处结束提取原数组元素。 slice 会提取原数组中索引从 begin 到 end 的所有元素(包含 begin,但不包含 end)。 slice(1,4) 会提取原数组中从第二个元素开始一直到第四个元素的所有元素 (索引为 1, 2, 3 的元素)。 如果该参数为负数,则它表示在原数组中的倒数第几个元素结束抽取。 slice(-2,-1) 表示抽取了原数组中的倒数第二个元素到最后一个元素。 如果 end 被省略,则 slice 会一直提取到原数组末尾。 如果 end 大于数组的长度,slice 也会一直提取到原数组末尾。 返回值: 一个含有被提取元素的新数组。
29. some() 测试数组中是不是至少有 1 个元素通过了被提供的函数测试。
some() 方法测试数组中是不是至少有 1 个元素通过了被提供的函数测试。它返回的是一个 Boolean 类型的值。如果用一个空数组进行测试,在任何情况下它返回的都是false。
const array = [1, 2, 3, 4, 5]; // checks whether an element is even const even = (element) => element % 2 === 0; console.log(array.some(even)); // expected output: true
示例:
- 判断数组元素中是否存在某个值
var fruits = ['apple', 'banana', 'mango', 'guava']; function checkAvailability(arr, val) { return arr.some(function(arrVal) { return val === arrVal; }); } checkAvailability(fruits, 'kela'); // false checkAvailability(fruits, 'banana'); // true 使用箭头函数判断数组元素中是否存在某个值: var fruits = ['apple', 'banana', 'mango', 'guava']; function checkAvailability(arr, val) { return arr.some(arrVal => val === arrVal); } checkAvailability(fruits, 'kela'); // false checkAvailability(fruits, 'banana'); // true
30. sort() 排序,并返回数组。
sort() 方法用原地算法对数组的元素进行排序,并返回数组。默认排序顺序是在将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列时构建的。
const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // expected output: Array ["Dec", "Feb", "Jan", "March"] const array1 = [1, 30, 4, 21, 100000]; array1.sort(); console.log(array1); // expected output: Array [1, 100000, 21, 30, 4]
语法:
// 无函数 sort() // 箭头函数 sort((a, b) => { /* … */ } ) // 比较函数 sort(compareFn) // 内联比较函数 sort(function compareFn(a, b) { /* … */ })
参数:
compareFn 可选 用来指定按某种顺序进行排列的函数。 如果省略,元素按照转换为的字符串的各个字符的 Unicode 位点进行排序。 a 第一个用于比较的元素。 b 第二个用于比较的元素。 描述: 如果指明了 compareFn ,那么数组会按照调用该函数的返回值排序。 即 a 和 b 是两个将要被比较的元素: 如果 compareFn(a, b) 大于 0,b 会被排列到 a 之前。 如果 compareFn(a, b) 小于 0,那么 a 会被排列到 b 之前; 如果 compareFn(a, b) 等于 0,a 和 b 的相对位置不变。
要比较数字而非字符串,比较函数可以简单的用 a 减 b,如下的函数将会将数组升序排列(如果它不包含 Infinity 和 NaN):
function compareNumbers(a, b) { return a - b; }
sort 方法可以使用 函数表达式 方便地书写:
const numbers = [4, 2, 5, 1, 3]; numbers.sort(function (a, b) { return a - b; }); console.log(numbers); // [1, 2, 3, 4, 5] // 或者 const numbers2 = [4, 2, 5, 1, 3]; numbers2.sort((a, b) => a - b); console.log(numbers2); // [1, 2, 3, 4, 5] a-b -> 升序 b-a -> 降序
31. splice() 通过删除或替换现有元素或者原地添加新的元素来修改数组。
splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。
语法:
splice(start) splice(start, deleteCount) splice(start, deleteCount, item1) splice(start, deleteCount, item1, item2, itemN)
参数:
- start
指定修改的开始位置(从 0 计数)。如果超出了数组的长度,则从数组末尾开始添加内容;如果是负值,则表示从数组末位开始的第几位(从 -1 计数,这意味着 -n 是倒数第 n 个元素并且等价于 array.length-n);如果负数的绝对值大于数组的长度,则表示开始位置为第 0 位。
- deleteCount 可选
整数,表示要移除的数组元素的个数。如果 deleteCount 大于 start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 start 位)。如果 deleteCount 被省略了,或者它的值大于等于array.length - start(也就是说,如果它大于或者等于start之后的所有元素的数量),那么start之后数组的所有元素都会被删除。如果 deleteCount 是 0 或者负数,则不移除元素。这种情况下,至少应添加一个新元素。
- item1, item2, ... 可选
要添加进数组的元素,从start 位置开始。如果不指定,则 splice() 将只删除数组元素。
返回值:
由被删除的元素组成的一个数组。如果只删除了一个元素,则返回只包含一个元素的数组。如果没有删除元素,则返回空数组。
示例:
- 从索引 2 的位置开始删除 0 个元素,插入“drum”和 "guitar"
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2, 0, 'drum', 'guitar'); // 运算后的 myFish: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"] // 被删除的元素:[], 没有元素被删除
- 从索引 2 的位置开始删除所有元素
var myFish = ['angel', 'clown', 'mandarin', 'sturgeon']; var removed = myFish.splice(2); // 运算后的 myFish: ["angel", "clown"] // 被删除的元素:["mandarin", "sturgeon"]
32. toString() 返回一个字符串,表示指定的数组及其元素。
toString() 方法返回一个字符串,表示指定的数组及其元素。
const array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); // expected output: "1,2,a,1a"
语法:
toString() 返回值: 一个表示数组所有元素的字符串。
33. unshift() 将一个或多个元素添加到数组的开头,并返回该数组的新长度。
const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // expected output: 5 console.log(array1); // expected output: Array [4, 5, 1, 2, 3]
示例:
const arr = [1, 2]; arr.unshift(0); // 调用的结果是 3,这是新的数组长度 // arr is [0, 1, 2] arr.unshift(-2, -1); // 新的数组长度为 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]); // 新的数组长度为 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, -6], [-5]); // 新的数组长度为 8 // arr is [ [-7, -6], [-5], [-4, -3], -2, -1, 0, 1, 2 ]
34. values() 返回一个新的对象,该对象包含数组每个索引的值。
values() 方法返回一个新的 Array Iterator 对象,该对象包含数组每个索引的值。
const array1 = ['a', 'b', 'c']; const iterator = array1.values(); for (const value of iterator) { console.log(value); } // expected output: "a" // expected output: "b" // expected output: "c"
返回值:
一个新的 Array 迭代对象。
示例:
- 使用 for ... of 循环进行迭代
const arr = ['a', 'b', 'c', 'd', 'e']; const iterator = arr.values(); for (const letter of iterator) { console.log(letter); } //"a" "b" "c" "d" "e"