JavaScript中的Array对象与其他编程语言中的数组一样,可以将多个项目的集合存储在单个变量名下,并具有用于执行常见数组操作的成员。

声明数组
有两种不同的方式可以声明数组。

使用new Array
通过new Array,我们可以指定希望存在于数组中的元素,如下所示:

const fruits = new Array('Apple', 'Banana');
console.log(fruits.length);

数组字面量表示法
使用数组字面量声明,我们可以指定数组将具有的值。如果我们不声明任何值,则数组将为空。

// 通过数组字面量创建一个有2个元素的'fruits'数组.
const fruits = ['Apple', 'Banana'];
console.log(fruits.length);

以下是Array对象的方法列表及描述。

1. forEach

forEach()方法将为每个数组元素执行一次指定的函数。

forEach()为数组中的每个元素按索引升序调用提供的callbackFn函数一次。它不会为已删除或未初始化的索引属性调用。

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. map

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. concat

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. push

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()方法将删除数组的最后一个元素并将该值返回给调用者。如果你在空数组上调用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

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

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()函数直接修改正在使用的数组。同时shift()返回数组中删除的项目。

shift()函数删除索引位置0的项目,并将索引号的值依次向下移动1。

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

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. join

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

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

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

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

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

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()方法接受整数值并返回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

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

some()方法测试数组中是不是至少有一个元素通过了函数实现的条件测试。如果在数组中找到这样的元素就返回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
文章目录