JavaScript 中的 15 种以上数组方法
JS 中的数组是什么?
Array 对象与其他编程语言中的数组一样,允许在单个变量名下存储多个项目的集合,并具有用于执行常见数组操作的成员。
声明数组
我们可以用两种不同的方式声明数组。
使用新数组
使用新的数组,我们可以指定我们想要存在于数组中的元素,如下所示:
const fruits = new Array('Apple', 'Banana');
console.log(fruits.length);
数组字面量表示法
使用数组字面量声明,我们指定数组将具有的值。如果我们不声明任何值,则数组将为空。
// 'fruits' array created using array literal notation.
const fruits = ['Apple', 'Banana'];
console.log(fruits.length);
JavaScript 数组方法
以下是 Array 对象的方法及其描述的列表。
1.forEach
forEach() 方法对每个数组元素执行一次提供的函数。
forEach() 会按升序对数组中的每个元素调用一次提供的回调函数。对于已删除或未初始化的索引属性,不会调用此函数。
array.forEach(callback[, thisObject]);
const array1 = ['a', 'b', 'c'];
array1.forEach(element => console.log(element));
// expected output: "a"
// expected output: "b"
// expected output: "c"
2.地图
Array.map() 方法允许你迭代一个数组并使用回调函数修改其元素。回调函数将在数组的每个元素上执行。
array.map(callback[, thisObject]);
let arr = [3, 4, 5, 6];
let modifiedArr = arr.map(function(element){
return element *3;
});
console.log(modifiedArr); // [9, 12, 15, 18]
Array.map() 方法通常用于对元素应用一些更改,无论是像上面的代码一样乘以特定的数字,还是执行应用程序可能需要的任何其他操作。
3.连接
在 JavaScript 中,concat() 是一个用于连接字符串的字符串方法。concat() 方法将一个或多个字符串值附加到调用字符串,然后将连接的结果作为新字符串返回。由于 concat() 方法是 String 对象的方法,因此必须通过 String 类的特定实例来调用它。
array.concat(value1, value2, ..., valueN);
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"]
4.推送
JavaScript 数组 push() 方法将给定元素添加到数组的末尾,并返回新数组的长度。
当你想将元素添加到数组末尾时,请使用 push()。
array.push(element1, ..., elementN);
const countries = ["Nigeria", "Ghana", "Rwanda"];
countries.push("Kenya");
console.log(countries); // ["Nigeria","Ghana","Rwanda","Kenya"]
5.流行
pop() 方法从数组中移除最后一个元素,并将该值返回给调用者。如果对空数组调用 pop(),则返回 undefined。
Array.prototype.shift() 的行为与 pop() 类似,但应用于数组中的第一个元素。
array.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"]
6.拼接
splice() 方法是一种通用方法,用于通过在数组的指定位置删除、替换或添加元素来更改数组的内容。本节将介绍如何使用此方法将元素添加到特定位置。
array.splice(index, howMany, [element1][, ..., elementN]);
const fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(2, 0, "Lemon", "Kiwi"); //Banana,Orange,Lemon,Kiwi,Apple,Mango
7.切片
slice() 方法将数组的一部分内容浅拷贝至一个新数组对象,该新数组对象从起始位置到结束位置(不包括结束位置),起始位置和结束位置代表数组中元素的索引。原始数组不会被修改。
array.slice( 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"]
8.shift
shift() 是一个内置的 JavaScript 函数,用于从数组中删除第一个元素。shift() 函数会直接修改你正在处理的 JavaScript 数组。shift() 返回你从数组中删除的元素。
shift() 函数删除索引位置 0 处的项目,并将未来索引号处的值向下移动一。
array.shift();
const array1 = [1, 2, 3];
const firstElement = array1.shift();
console.log(array1);
// expected output: Array [2, 3]
console.log(firstElement);
// expected output: 1
9.取消移位
unshift() 方法将给定的值插入到类似数组的对象的开头。
Array.prototype.push() 的行为与 unshift() 类似,但应用于数组的末尾。
array.unshift( element1, ..., elementN );
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]
10.加入
JavaScript 数组 join() 是一个内置方法,它通过连接数组的所有元素来创建并返回新的字符串。join() 方法将数组的所有元素连接到字符串中并返回该字符串。指定的分隔符将分隔数组中的元素。默认分隔符为逗号 (,)。
array.join(separator);
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"
11.每个
every() 方法测试数组中的所有元素是否通过了所提供函数实现的测试。它返回一个布尔值。
array.every(callback[, thisObject]);
const isBelowThreshold = (currentValue) => currentValue < 40;
const array1 = [1, 30, 39, 29, 10, 13];
console.log(array1.every(isBelowThreshold));
// expected output: true
12.过滤器
filter() 方法创建给定数组的一部分的浅表副本,过滤掉给定数组中通过所提供函数实现的测试的元素。
array.filter(callback[, thisObject]);
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"]
13.indexOf
indexOf() 方法返回数组中给定元素的第一个索引,如果不存在则返回 -1。
array.indexOf(searchElement[, fromIndex]);
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
14.减少
reduce() 方法会按顺序对数组中的每个元素执行用户提供的“reducer”回调函数,并传入前一个元素计算的返回值。对数组的所有元素运行 Reducer 的最终结果是一个值。
array.reduce(callback[, initialValue]);
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)
15.反向
reverse() 方法将数组反转,并返回对原数组的引用。此时,数组中的第一个元素将成为最后一个元素,而最后一个元素将成为第一个元素。换句话说,数组中元素的顺序将朝着与先前相反的方向旋转。
array.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"]
16.排序
sort() 方法对数组元素进行原地排序,并返回已排序的原数组的引用。默认排序顺序为升序,其基础是将元素转换为字符串,然后比较它们的 UTF-16 代码单元值序列。
array.sort( compareFunction );
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]
17.toString
toString() 方法返回表示该对象的字符串。
array.toString();
function Dog(name) {
this.name = name;
}
const dog1 = new Dog('Gabby');
Dog.prototype.toString = function dogToString() {
return `${this.name}`;
};
console.log(dog1.toString());
// expected output: "Gabby"
18.at
at() 方法接受一个整数值并返回该索引处的项,允许正整数和负整数。负整数从数组中的最后一项开始倒数。
array.at(index)
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"
19.查找
find() 方法返回数组中第一个满足指定测试函数的元素。如果没有值满足测试函数,则返回 undefined。
array.find(function(currentValue, index, arr),thisValue)
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
20.一些
some() 方法测试数组中是否至少有一个元素通过了所提供函数实现的测试。如果在数组中找到一个元素,且所提供函数的测试结果为 true,则返回 true;否则返回 false。该方法不会修改数组。
array.some(callback[, thisObject]);
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