你应该需要的25个Javascript数组方法,建议收藏!

286 阅读15分钟

1、join() 方法

  • 功能:将数组按指定的分隔符转成字符串,默认分隔符为逗号(,)。
  • 注意:该方法不会改变原始数组。
  • 语法:array.join(separator)
  • 参数:
    • separator:可选。要使用的分隔符。如果省略,元素用逗号分隔。
const arr = ['a', 'b', 'c', 'd'];
console.log(arr.join()); // 'a,b,c,d'
console.log(arr.join('/')); // 'a/b/c/d'
console.log(arr); // ["a", "b", "c", "d"]

2、concat() 方法

  • 功能:用于连接两个或多个数组。
  • 注意:该方法不会改变原始数组,而是返回一个新数组,其中包含已连接数组的值。
  • 语法:array1.concat(array2, array3, ..., arrayX)
  • 参数:
    • array2, array3, ..., arrayX:必需。要连接的数组。
const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
console.log(arr1.concat(arr2)); // [1, 2, 3, 4, 5, 6]
// 原数组不会改变
console.log(arr1); // [1, 2, 3]
console.log(arr2); // [4, 5, 6]

3、pop() 方法

  • 功能:移除数组的最后一个元素,并返回该元素。
  • 注意:该方法会改变原始数组。
  • 语法:array.pop()
  • 参数:无参数。
const arr = [1, 2, 3, 4, 5, 6];
console.log(arr.pop()); // 6
// 原始数组被改变
console.log(arr); // [1, 2, 3, 4, 5]

4、shift() 方法

  • 功能:删除数组的第一项。
  • 注意:该方法会改变原始数组,返回值是被删除的项。
  • 语法:array.shift()
  • 参数:无参数。
const arr = [1, 2, 3, 4, 5, 6];
console.log(arr.shift()); // 1
// 原始数组发生改变
console.log(arr); // [2, 3, 4, 5, 6]

5、unshift() 方法

  • 功能:在数组的开头添加一项或多项,并返回新的数组长度。
  • 注意:该方法会改变原始数组。
  • 语法:array.unshift(item1, item2, ..., itemX)
  • 参数:
    • array.unshift(item1, item2, ..., itemX):必需。要添加到数组开头的项。
const arr = ["apple", "pear", "banana"];
console.log(arr.unshift("peach")); // 4
console.log(arr.unshift("peach", "cherries", "strawberry")); // 7
// 原始数组发生改变
console.log(arr); // ["peach", "cherries", "strawberry", "peach", "apple", "pear", "banana"]

6、push() 方法

  • 功能:向数组末尾添加一项或多项,并返回新的数组长度。
  • 注意:该方法会改变原始数组。
  • 语法:array.push(item1, item2, ..., itemX)
  • 参数:
    • item1, item2, ..., itemX:必需。要添加到数组末尾的项目。
const arr = ["apple", "pear", "banana"];
console.log(arr.push("peach")); // 4
console.log(arr.push("peach", "cherries", "strawberry")); // 7
console.log(arr); // ["apple", "pear", "banana", "peach", "peach", "cherries", "strawberry"]

7、reverse() 方法

  • 功能:反转数组中元素的顺序,并返回反转后的数组。
  • 注意:该方法会改变原始数组。
  • 语法:array.reverse()
  • 参数:无参数。
const arr = [1, 2, 3, 4];
console.log(arr.reverse()); // [4, 3, 2, 1]
console.log(arr); // [4, 3, 2, 1]

8、sort() 方法

  • 功能:对数组的项目进行排序。排序顺序可以是按字母或数字,也可以是升序(向上)或降序(向下)。默认情况下,sort()方法将按字母和升序将值作为字符串进行排序。
  • 注意:该方法会改变原始数组。
  • 语法:array.sort(compareFunction)
  • 参数:
    • compareFunction:可选。定义替代排序顺序的函数。该函数应返回负值、零值或正值,具体取决于参数。
// 按字母顺序排序
const arr = ["pear", "banana", "apple", "cherries"];
console.log(arr.sort()); // ["apple", "banana", "cherries", "pear"]

// 升序排序
const arr = [15, 28, 3, 66, 5];
function sortNumber(a, b) {
  return a - b
}
console.log(arr.sort(sortNumber)); // [3, 5, 15, 28, 66]

// 降序排序
const arr = [15, 28, 3, 66, 5];
function sortNumber(a, b) {
  return b - a
}
console.log(arr.sort(sortNumber)); // [66, 28, 15, 5, 3]

9、toString() 方法

javascript中的toString()方法,主要用于Array、Boolean、Date、Number、Error、Function等对象。

  • Array.toString():将数组转换成以逗号分割字符串,并且返回这个字符串。
const arr = ["apple", "pear", "banana", "grapes"];
arr.toString(); // 'apple,pear,banana,grapes'
  • Boolean.toString():将布尔值转换为字符串。
const b = new Boolean();
console.log(b); // Boolean {false}
console.log(b.toString()); // 'false'
console.log((1 === 1).toString()); // 'true'
console.log((1 === "1").toString()); // 'false'
  • Date.toString():将Date对象转换为字符串。
const date = new Date();
console.log(date); // Wed Mar 09 2022 08:04:26 GMT+0800 (中国标准时间)
console.log(date.toString()); // 'Wed Mar 09 2022 08:04:26 GMT+0800 (中国标准时间)'
console.log(typeof date); // object
console.log(typeof date.toString()); // string
  • Number.toString():将数字转换为字符串,根据所传的参数指定Number对象的字符串表示形式。
语法:numObj.toString([radix])
参数:radix:指定要用于数字到字符串的转换的基数(从236)。如果未指定 radix 参数,则默认值为 10。
注意:
    如果 toString() 的 radix 参数不在 236 之间,将会抛出一个错误信息 RangeError。
    如果转换的基数大于10,则会使用字母来表示大于9的数字,比如基数为16的情况,则使用a到f的字母来表示1015。
    如果基数没有指定,则使用 10。
    如果对象是负数,则会保留负号。即使radix是2时也是如此:返回的字符串包含一个负号(-)前缀和正数的二进制表示,不是数值的二进制补码。
    进行数字到字符串的转换时,建议用小括号将要转换的目标括起来,防止出错。
const num = 10;
console.log(num.toString()); // '10'
console.log(num.toString(2)); // '1010'
console.log(num.toString(8)); // '12'
console.log(num.toString(16)); // 'a'
console.log((-10).toString(2)); // '-1010'
console.log((-0xff).toString(2)); // '-11111111'
console.log(num.toString(50)); // Uncaught RangeError
  • Error.toString():将Error对象转换为字符串表示。
const e = new Error('fatal error');
console.log(e.toString()); // 'Error: fatal error'

e.name = undefined;
console.log(e.toString()); // 'Error: fatal error'

e.name = '';
console.log(e.toString()); // 'fatal error'

e.message = undefined;
console.log(e.toString()); // ''

e.name = 'hello';
console.log(e.toString()); // 'hello'
  • Function.toString():把函数转换成字符串,返回一个表示当前函数源代码的字符串。
function sum(a, b) {
  return a + b;
}
console.log(sum.toString());
// 控制台打印输出函数源代码的字符串
// 'function sum(a, b) {
//    return a + b;
// }'

10、splice() 方法

  • 功能:向数组中添加、或从数组中删除、或替换数组中的元素,然后返回被删除或被替换的元素。
  • 注意:该方法会改变原始数组。
  • 语法:array.splice(index, howmany, item1, ....., itemX)
  • 参数:
    • index:必需。整数,指定在什么位置添加/删除项目,使用负值指定从数组末尾开始的位置。
    • howmany:可选。要删除的项目数。如果设置为 0,则不会删除任何项目。
    • item1, ....., itemX:可选。要添加到数组中的新项目。
const arr = ['apple', 'pear', 'banana', 'peach', 'cherries', 'strawberry'];
console.log(arr.splice(2, 2)); // 从位置2开始,删除2项,返回被删除的项 ["banana", "peach"]
console.log(arr); // 原数组改变 ["apple", "pear", "cherries", "strawberry"]

console.log(arr.splice(2, 0, 'watermelon')); // 第2个参数设置为0,不会删除任何项,返回 []
console.log(arr); // 原数组改变 ["apple", "pear", "watermelon", "banana", "peach", "cherries", "strawberry"]

console.log(arr.splice(2, 3, 'watermelon', 'mango')); // 从位置2开始,删除3项,并添加两项,返回被删除的项 ["banana", "peach", "cherries"]
console.log(arr); // 原数组改变 ["apple", "pear", "watermelon", "mango", "strawberry"]

11、slice() 方法

  • 功能:截取指定位置的数组,并且返回截取的数组。
  • 注意:该方法不会改变原始数组。
  • 语法:array.slice(start, end)
  • 参数:
    • start:可选。整数,指定从哪里开始选择(第一个元素的索引为 0)。使用负数从数组的末尾进行选择。如果省略,则类似于 "0"。
    • end:可选。整数,指定结束选择的位置。如果省略,将选择从开始位置到数组末尾的所有元素。使用负数从数组末尾进行选择。
    • start 和 end 都可以为负数,负数时表示从最后一位开始算起,如 -1 表示最后一位。
const arr = ['apple', 'pear', 'banana', 'peach', 'cherries', 'strawberry'];

// 从数组第3项开始截取到末尾的所有元素
console.log(arr.slice(3)); // ["peach", "cherries", "strawberry"]

// 从数组第3项开始截取,截取到数组的第4项
console.log(arr.slice(3, 4)); // ["peach"]

// 从数组的倒数第3项开始,截取到数组的倒数第1项
console.log(arr.slice(-3, -1)); // ["peach", "cherries"]

// 原数组不会改变
console.log(arr); // ["apple", "pear", "banana", "peach", "cherries", "strawberry"]

12、valueOf() 方法

  • 功能:数组对象的默认方法,返回数组本身。
  • 注意:该方法不会改变原始数组。
  • 语法:array.valueOf()
  • 参数:无参数。
const arr = [15, 28, 3, 66, 5];
console.log(arr.valueOf()); // [15, 28, 3, 66, 5]
console.log(arr); // [15, 28, 3, 66, 5]

13、indexOf() 方法

  • 功能:在数组中搜索指定的值,并返回其位置。搜索将从指定位置开始,如果未指定开始位置,则从头开始,并在数组末尾结束搜索。如果未找到指定的值,则返回 -1。如果该指定的值在数组中出现多次,则返回第一次出现的位置。
  • 注意:该方法不会改变原始数组。数组第一项的位置为 0,第二项的位置为 1,依此类推。
  • 语法:array.indexOf(item, start)
  • 参数:
    • item:必需。要搜索的项目。
    • start:可选。规定在数组中开始检索的位置。它的合法取值是 0 到 array.length - 1。如省略该参数,则将从数组的第一项开始检索。
const arr = ["pear", "banana", "apple", "pear", "cherries"];
console.log(arr.indexOf("pear")); // 0
console.log(arr.indexOf("pear", 2)); // 3
console.log(arr.indexOf("pear", 6)); // -1 数组的长度只有5
console.log(arr.indexOf("strawberry")); // -1
// 不会改变原始数组
console.log(arr); // ["pear", "banana", "apple", "pear", "cherries"]

14、lastIndexOf() 方法

  • 功能:在数组中搜索指定的值,并返回其位置。搜索将从指定位置开始,如果未指定开始位置,则从末尾开始,并在数组的开头结束搜索。如果未找到指定的值,则返回 -1。如果要搜索的值出现多次,则返回最后一次出现的位置。
  • 注意:该方法不会改变原始数组。
  • 语法:array.lastIndexOf(item, start)
  • 参数:
    • item:必需。要搜索的项目。
    • start:可选。从哪里开始搜索。规定在数组中开始检索的位置。它的合法取值是 0 到 array.length - 1。如省略该参数,则从数组的最后一项开始检索。
const arr = ["pear", "banana", "apple", "pear", "cherries"];
console.log(arr.lastIndexOf("pear")); // 3
console.log(arr.lastIndexOf("pear", 2)); // 0
console.log(arr.lastIndexOf("strawberry")); // -1
// 不会改变原始数组
console.log(arr); // ["pear", "banana", "apple", "pear", "cherries"]

15、includes() 方法

  • 功能:判断数组是否包含指定的元素。如果数组包含元素,则此方法返回 true,否则返回 false。
  • 注意:该方法区分大小写。
  • 语法:array.includes(element, start)
  • 参数:
    • element:必需。要搜索的元素。
    • start:可选。默认 0。在数组中的哪个位置开始搜索。
const arr = ["pear", "banana", "apple", "pear", "cherries"];
console.log(arr.includes("banana")); // true
console.log(arr.includes("Banana")); // false
console.log(arr.includes("banana", 2)); // false
console.log(arr); // ["pear", "banana", "apple", "pear", "cherries"]

16、from() 方法

  • 功能:从具有 length 属性或可迭代对象的任何对象返回 Array 对象。
  • 语法:Array.from(object, mapFunction, thisValue)
  • 参数:
    • object:必需。需转换为数组的对象。
    • mapFunction:可选。如果指定了该参数,新数组中的每个元素会执行该回调函数。
    • thisValue:可选。执行 mapFunction 时用作 this 的值。
// 1、从 String 中生成数组
console.log(Array.from('abc')); // ["a", "b", "c"]

// 2、从 Map 生成数组
const map = new Map();
map.set('key1', 1);
map.set('key2', 2);
map.set('key3', 3);
console.log(Array.from(map)); // [["key1", 1], ["key2", 2], ["key3", 3]]
console.log(Array.from(map.keys())); // ["key1", "key2", "key3"]
console.log(Array.from(map.values())); // [1, 2, 3]

// 3、从 Set 生成数组
const set = new Set(['a', 'b', 'c', 'a']);
console.log(Array.from(set)); // ["a", "b", "c"]

// 4、从 类数组对象 生成数组
function func() {
  return Array.from(arguments);
}
const f = func(1, 2, 3);
console.log(f); // [1, 2, 3]

17、isArray() 方法

  • 功能:判断确定对象是否为数组。如果是,返回 true,否则返回 false。
  • 语法:Array.isArray(obj)
  • 参数:
    • obj:需要检测的值。
console.log(Array.isArray([])); // true
console.log(Array.isArray([1, 2, 3])); // true
console.log(Array.isArray(new Array())); // true
console.log(Array.isArray(new Array('a', 'b', 'c'))); // true
console.log(Array.isArray(Array.prototype)); // true

console.log(Array.isArray()); // false
console.log(Array.isArray({})); // false
console.log(Array.isArray(null)); // false
console.log(Array.isArray(undefined)); // false
console.log(Array.isArray('abc')); // false
console.log(Array.isArray(1234)); // false
console.log(Array.isArray(true)); // false
console.log(Array.isArray(false)); // false

18、map() 方法

  • 功能:为每个数组元素调用函数的结果创建新数组。按顺序为数组中的每个元素调用一次提供的函数。返回一个新数组,数组中的元素为原始数组元素调用函数处理后的值。
  • 注意:该方法不会对空数组进行检测,不会改变原始数组。
  • 语法:array.map(function(currentValue, index, arr), thisValue)
  • 参数:
    • function(currentValue, index, arr):必需。为数组中的每个元素运行的函数。currentValue:必需。当前元素的值。index:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • thisValue:可选。要传递给函数以用作其 "this" 值的值。如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。
const arr = [1, 2, 3, 4];
console.log(arr.map(item => item * 2)); // [2, 4, 6, 8]
console.log(arr); // [1, 2, 3, 4]

19、filter() 方法

  • 功能:创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
  • 注意:该方法不会对空数组进行检测,不会改变原始数组。
  • 语法:array.filter(function(currentValue, index, arr), thisValue)
  • 参数:
    • function(currentValue, index, arr):必需。为数组中的每个元素运行的函数。currentValue:必需。当前元素的值。index:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • thisValue:可选。要传递给函数以用作其 "this" 值的值。如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。
const arr = [1, 2, 3, 4];
console.log(arr.filter(item => item % 2 === 0)); // [2, 4]
console.log(arr.filter(item => item > 5)); // []
console.log(arr); // [1, 2, 3, 4]

20、reduce() 方法

  • 功能:将数组缩减为单个值。为数组的每个值(从左到右)执行提供的函数。函数的返回值存储在累加器中(结果/总计)。
  • 注意:reduce() 对于空数组是不会执行回调函数的。
  • 语法:array.reduce(function(total, currentValue, currentIndex, arr), initialValue)
  • 参数:
    • function(total, currentValue, currentIndex, arr):必需。为数组中的每个元素运行的函数。total:必需。initialValue,或函数先前返回的值。currentValue:必需。当前元素的值。currentIndex:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • initialValue:可选。作为初始值传递给函数的值。
const arr = [1, 2, 3, 4, 5];
const sum = (x, y) => x + y;
console.log(arr.reduce(sum)); // 15
console.log(arr.reduce(sum, 5)); // 20
console.log(arr); // [1, 2, 3, 4, 5]

21、find() 方法

  • 功能:返回数组中第一个通过测试的元素的值。对数组中存在的每个元素执行一次函数:如果找到函数返回 true 值的数组元素,则 find() 返回该数组元素的值(并且不检查剩余值),否则返回 undefined。
  • 注意:该方法对于空数组,函数是不会执行的,不会改变数组的原始值。
  • 语法:array.find(function(currentValue, index, arr), thisValue)
  • 参数:
    • function(currentValue, index, arr):必需。为数组中的每个元素运行的函数。currentValue:必需。当前元素的值。index:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • thisValue:可选。要传递给函数以用作其 "this" 值的值。如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。
const arr = [1, 2, 3, 4, 5];
console.log(arr.find(item => item > 2)); // 3
console.log(arr.find(item => item > 5)); // undefined
console.log(arr); // [1, 2, 3, 4, 5]

22、findIndex() 方法

  • 功能:返回数组中满足提供的测试函数的第一个元素的索引。当数组中的元素在测试条件时返回 true 时,findIndex() 返回符合条件的元素的索引位置,之后的值不会再调用执行函数。如果没有符合条件的元素返回 -1。
  • 注意:该方法对于空数组,函数是不会执行的,不会改变数组的原始值。
  • 语法:array.findIndex(function(currentValue, index, arr), thisValue)
  • 参数:
    • function(currentValue, index, arr):必需。为数组中的每个元素运行的函数。currentValue:必需。当前元素的值。index:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • thisValue:可选。要传递给函数以用作其 "this" 值的值。如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。
const arr = [1, 2, 3, 4, 5];
console.log(arr.findIndex(item => item > 2)); // 2
console.log(arr.findIndex(item => item > 5)); // -1
console.log(arr); // [1, 2, 3, 4, 5]

23、some() 方法

  • 功能:检查数组中的任何元素是否通过测试(作为函数提供),对数组中存在的每个元素执行一次函数:如果找到函数返回真值的数组元素,some() 返回真(并且不检查剩余值),否则返回 false。
  • 注意:该方法不对没有值的数组元素不执行函数。不会改变数组的原始值。
  • 语法:array.some(function(currentValue, index, arr), thisValue)
  • 参数:
    • function(currentValue, index, arr):必需。为数组中的每个元素运行的函数。currentValue:必需。当前元素的值。index:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • thisValue:可选。要传递给函数以用作其 "this" 值的值。如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。
const arr = [1, 2, 3, 4, 5];
console.log(arr.some(item => item > 2)); // true
console.log(arr.some(item => item > 5)); // false
console.log(arr); // [1, 2, 3, 4, 5]

24、every() 方法

  • 功能:检查数组中的所有元素是否都通过了测试(被作为函数提供),对数组中存在的每个元素执行一次函数:如果找到函数返回 false 值的数组元素,every() 返回 false(并且不检查剩余值),如果没有出现 false,every() 返回 true。
  • 注意:该方法不对没有值的数组元素不执行函数。不会改变数组的原始值。
  • 语法:array.some(function(currentValue, index, arr), thisValue)
  • 参数:
    • function(currentValue, index, arr):必需。为数组中的每个元素运行的函数。currentValue:必需。当前元素的值。index:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • thisValue:可选。要传递给函数以用作其 "this" 值的值。如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。
const arr = [1, 2, 3, 4, 5];
console.log(arr.every(item => item > 3)); // false
console.log(arr); // [1, 2, 3, 4, 5]

const arr = [5, 6, 7, 4, 5];
console.log(arr.every(item => item > 3)); // false
console.log(arr); // [5, 6, 7, 4, 5]

25、forEach() 方法

  • 功能:按顺序为数组中的每个元素调用一次函数。
  • 注意:对于没有值的数组元素,不执行forEach()方法。
  • 语法:array.forEach(function(currentValue, index, arr), thisValue)
  • 参数:
    • function(currentValue, index, arr):必需。为数组中的每个元素运行的函数。currentValue:必需。当前元素的值。index:可选。当前元素的数组索引。arr:可选。当前元素所属的数组对象。
    • thisValue:可选。要传递给函数以用作其 "this" 值的值。如果此参数为空,则值 "undefined" 将作为其 "this" 值传递。
const arr = [5, 6, 7, , 9];
function outputEachElement(element, index, array) {
  console.log('a[' + index + '] = ' + element);
}
// 注意索引 3 被跳过了,因为在数组的这个位置没有值
arr.forEach(outputEachElement);
// a[0] = 5
// a[1] = 6
// a[2] = 7
// a[4] = 9
console.log(arr); // [5, 6, 7, , 9]