Array 对象方法

方法 描述
concat() 连接两个或更多的数组,并返回结果。
copyWithin() 从数组的指定位置拷贝元素到数组的另一个指定位置中。
entries() 返回数组的可迭代对象。
every() 检测数值元素的每个元素是否都符合条件。
fill() 使用一个固定值来填充数组。
filter() 检测数值元素,并返回符合条件所有元素的数组。
find() 返回符合传入测试(函数)条件的数组元素。
findIndex() 返回符合传入测试(函数)条件的数组元素索引。
forEach() 数组每个元素都执行一次回调函数。
from() 通过给定的对象中创建一个数组。
includes() 判断一个数组是否包含一个指定的值。
indexOf() 搜索数组中的元素,并返回它所在的位置。
isArray() 判断对象是否为数组。
join() 把数组的所有元素放入一个字符串。
keys() 返回数组的可迭代对象,包含原始数组的键(key)。
lastIndexOf() 搜索数组中的元素,并返回它最后出现的位置。
map() 通过指定函数处理数组的每个元素,并返回处理后的数组。
pop() 删除数组的最后一个元素并返回删除的元素。
push() 向数组的末尾添加一个或更多元素,并返回新的长度。
reduce() 将数组元素计算为一个值(从左到右)。
reduceRight() 将数组元素计算为一个值(从右到左)。
reverse() 反转数组的元素顺序。
shift() 删除并返回数组的第一个元素。
slice() 选取数组的的一部分,并返回一个新数组。
some() 检测数组元素中是否有元素符合指定条件。
sort() 对数组的元素进行排序。
splice() 从数组中添加或删除元素。
toString() 把数组转换为字符串,并返回结果。
unshift() 向数组的开头添加一个或更多元素,并返回新的长度。
valueOf() 返回数组对象的原始值。

Array - Javascript | MDN

Splice

splice() 方法通过删除或替换现有元素或者原地添加新的元素来修改数组,并以数组形式返回被修改的内容。此方法会改变原数组。

  1. array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
  2. const months = ['Jan', 'March', 'April', 'June'];
  3. months.splice(1, 0, 'Feb');
  4. // inserts at index 1
  5. console.log(months);
  6. // expected output: Array ["Jan", "Feb", "March", "April", "June"]
  7. months.splice(4, 1, 'May');
  8. // replaces 1 element at index 4
  9. console.log(months);
  10. // expected output: Array ["Jan", "Feb", "March", "April", "May"]

示例

  • 从第 2 位开始删除 0 个元素,插入“drum”
  1. var myFish = ["angel", "clown", "mandarin", "sturgeon"];
  2. var removed = myFish.splice(2, 0, "drum");
  3. // 运算后的 myFish: ["angel", "clown", "drum", "mandarin", "sturgeon"]
  4. // 被删除的元素: [], 没有元素被删除
  • 从第 2 位开始删除 0 个元素,插入“drum” 和 “guitar”
  1. var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
  2. var removed = myFish.splice(2, 0, 'drum', 'guitar');
  3. // 运算后的 myFish: ["angel", "clown", "drum", "guitar", "mandarin", "sturgeon"]
  4. // 被删除的元素: [], 没有元素被删除
  • 从第 3 位开始删除 1 个元素
  1. var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
  2. var removed = myFish.splice(3, 1);
  3. // 运算后的 myFish: ["angel", "clown", "drum", "sturgeon"]
  4. // 被删除的元素: ["mandarin"]
  • 从第 2 位开始删除 1 个元素,插入“trumpet”
  1. var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
  2. var removed = myFish.splice(2, 1, "trumpet");
  3. // 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"]
  4. // 被删除的元素: ["drum"]
  • 从第 0 位开始删除 2 个元素,插入”parrot”、”anemone”和”blue”
  1. var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
  2. var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
  3. // 运算后的 myFish: ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
  4. // 被删除的元素: ["angel", "clown"]
  • 从第 2 位开始删除 2 个元素
  1. var myFish = ['parrot', 'anemone', 'blue', 'trumpet', 'sturgeon'];
  2. var removed = myFish.splice(myFish.length - 3, 2);
  3. // 运算后的 myFish: ["parrot", "anemone", "sturgeon"]
  4. // 被删除的元素: ["blue", "trumpet"]
  • 从倒数第 2 位开始删除 1 个元素
  1. var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
  2. var removed = myFish.splice(-2, 1);
  3. // 运算后的 myFish: ["angel", "clown", "sturgeon"]
  4. // 被删除的元素: ["mandarin"]
  • 从第 2 位开始删除所有元素
  1. var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
  2. var removed = myFish.splice(2);
  3. // 运算后的 myFish: ["angel", "clown"]
  4. // 被删除的元素: ["mandarin", "sturgeon"]

Slice

**slice()** 方法返回一个新的数组对象,这一对象是一个由 beginend 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。

  1. arr.slice([begin[, end]])
  2. const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
  3. console.log(animals.slice(2));
  4. // expected output: Array ["camel", "duck", "elephant"]
  5. console.log(animals.slice(2, 4));
  6. // expected output: Array ["camel", "duck"]
  7. console.log(animals.slice(1, 5));
  8. // expected output: Array ["bison", "camel", "duck", "elephant"]

示例

  • 返回现有数组的一部分
  1. var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
  2. var citrus = fruits.slice(1, 3);
  3. // fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
  4. // citrus contains ['Orange','Lemon']

译者注:citrus [n.] 柑橘类果实

  • 使用 slice

`<br /> 在下例中,slicemyCar中创建了一个新数组newCar。两个数组都包含了一个myHonda对象的引用。当myHondacolor属性改变为purple`,则两个数组中的对应元素都会随之改变。

  1. // 使用 slice 方法从 myCar 中创建一个 newCar。
  2. var myHonda = { color: 'red', wheels: 4, engine: { cylinders: 4, size: 2.2 } };
  3. var myCar = [myHonda, 2, "cherry condition", "purchased 1997"];
  4. var newCar = myCar.slice(0, 2);
  5. // 输出 myCar、newCar 以及各自的 myHonda 对象引用的 color 属性。
  6. console.log(' myCar = ' + JSON.stringify(myCar));
  7. console.log('newCar = ' + JSON.stringify(newCar));
  8. console.log(' myCar[0].color = ' + JSON.stringify(myCar[0].color));
  9. console.log('newCar[0].color = ' + JSON.stringify(newCar[0].color));
  10. // 改变 myHonda 对象的 color 属性.
  11. myHonda.color = 'purple';
  12. console.log('The new color of my Honda is ' + myHonda.color);
  13. //输出 myCar、newCar 中各自的 myHonda 对象引用的 color 属性。
  14. console.log(' myCar[0].color = ' + myCar[0].color);
  15. console.log('newCar[0].color = ' + newCar[0].color);

上述代码输出:

  1. myCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2,
  2. 'cherry condition', 'purchased 1997']
  3. newCar = [{color: 'red', wheels: 4, engine: {cylinders: 4, size: 2.2}}, 2]
  4. myCar[0].color = red
  5. newCar[0].color = red
  6. The new color of my Honda is purple
  7. myCar[0].color = purple
  8. newCar[0].color = purple
  • 类数组(Array-like)对象

slice 方法可以用来将一个类数组(Array-like)对象/集合转换成一个新数组。你只需将该方法绑定到这个对象上。 一个函数中的 arguments 就是一个类数组对象的例子。

  1. function list() {
  2. return Array.prototype.slice.call(arguments);
  3. }
  4. var list1 = list(1, 2, 3); // [1, 2, 3]

除了使用 Array.prototype.slice.call(``arguments``),你也可以简单的使用 [].slice.call(arguments) 来代替。另外,你可以使用 bind 来简化该过程。

  1. var unboundSlice = Array.prototype.slice;
  2. var slice = Function.prototype.call.bind(unboundSlice);
  3. function list() {
  4. return slice(arguments);
  5. }
  6. var list1 = list(1, 2, 3); // [1, 2, 3]

Indexof, LastIndexof

**indexOf()**方法返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

**lastIndexOf()** 方法返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1。从数组的后面向前查找,从 fromIndex 处开始。

  1. arr.indexOf(searchElement[, fromIndex])
  2. arr.lastIndexOf(searchElement[, fromIndex])
  3. const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
  4. console.log(beasts.indexOf('bison'));
  5. // expected output: 1
  6. // start from index 2
  7. console.log(beasts.indexOf('bison', 2));
  8. // expected output: 4
  9. console.log(beasts.indexOf('giraffe'));
  10. // expected output: -1

示例

  • 使用indexOf

以下例子使用indexOf方法确定多个值在数组中的位置。

  1. var array = [2, 5, 9];
  2. array.indexOf(2); // 0
  3. array.indexOf(7); // -1
  4. array.indexOf(9, 2); // 2
  5. array.indexOf(2, -1); // -1
  6. array.indexOf(2, -3); // 0
  • 找出指定元素出现的所有位置
  1. var indices = [];
  2. var array = ['a', 'b', 'a', 'c', 'a', 'd'];
  3. var element = 'a';
  4. var idx = array.indexOf(element);
  5. while (idx != -1) {
  6. indices.push(idx);
  7. idx = array.indexOf(element, idx + 1);
  8. }
  9. console.log(indices);
  10. // [0, 2, 4]
  • 判断一个元素是否在数组里,不在则更新数组
  1. function updateVegetablesCollection (veggies, veggie) {
  2. if (veggies.indexOf(veggie) === -1) {
  3. veggies.push(veggie);
  4. console.log('New veggies collection is : ' + veggies);
  5. } else if (veggies.indexOf(veggie) > -1) {
  6. console.log(veggie + ' already exists in the veggies collection.');
  7. }
  8. }
  9. var veggies = ['potato', 'tomato', 'chillies', 'green-pepper'];
  10. // New veggies collection is : potato,tomato,chillies,green-papper,spinach
  11. updateVegetablesCollection(veggies, 'spinach');
  12. // spinach already exists in the veggies collection.
  13. updateVegetablesCollection(veggies, 'spinach');

every

**every()** 方法测试一个数组内的所有元素是否都能通过某个指定函数的测试。它返回一个布尔值。

  1. arr.every(callback[, thisArg])
  2. const isBelowThreshold = (currentValue) => currentValue < 40;
  3. const array1 = [1, 30, 39, 29, 10, 13];
  4. console.log(array1.every(isBelowThreshold));
  5. // expected output: true

例子

  • 检测所有数组元素的大小

下例检测数组中的所有元素是否都大于 10。

  1. function isBigEnough(element, index, array) {
  2. return element >= 10;
  3. }
  4. [12, 5, 8, 130, 44].every(isBigEnough); // false
  5. [12, 54, 18, 130, 44].every(isBigEnough); // true
  • 使用箭头函数

箭头函数为上面的检测过程提供了更简短的语法。

  1. [12, 5, 8, 130, 44].every(x => x >= 10); // false
  2. [12, 54, 18, 130, 44].every(x => x >= 10); // true

forEach

**forEach()** 方法对数组的每个元素执行一次提供的函数。

  1. arr.forEach(callback(currentValue [, index [, array]])[, thisArg]);
  2. const array1 = ['a', 'b', 'c'];
  3. array1.forEach(element => console.log(element));
  4. // expected output: "a"
  5. // expected output: "b"
  6. // expected output: "c"

示例

  • 不对未初始化的值进行任何操作(稀疏数组)

如你所见,37 之间空缺的数组单元未被 forEach() 调用 callback 函数,或进行任何其他操作。

  1. const arraySparse = [1,3,,7];
  2. let numCallbackRuns = 0;
  3. arraySparse.forEach(function(element){
  4. console.log(element);
  5. numCallbackRuns++;
  6. });
  7. console.log("numCallbackRuns: ", numCallbackRuns);
  8. // 1
  9. // 3
  10. // 7
  11. // numCallbackRuns: 3
  • 将 for 循环转换为 forEach
  1. const items = ['item1', 'item2', 'item3'];
  2. const copy = [];
  3. // before
  4. for (let i=0; i<items.length; i++) {
  5. copy.push(items[i]);
  6. }
  7. // after
  8. items.forEach(function(item){
  9. copy.push(item);
  10. });

map

**map()** 方法创建一个新数组,其结果是该数组中的每个元素都调用一个提供的函数后返回的结果。

  1. const array1 = [1, 4, 9, 16];
  2. // pass a function to map
  3. const map1 = array1.map(x => x * 2);
  4. console.log(map1);
  5. // expected output: Array [2, 8, 18, 32]

示例

  • 求数组中每个元素的平方根

下面的代码创建了一个新数组,值为原数组中对应数字的平方根。

  1. var numbers = [1, 4, 9];
  2. var roots = numbers.map(Math.sqrt);
  3. // roots的值为[1, 2, 3], numbers的值仍为[1, 4, 9]
  • 使用 map 重新格式化数组中的对象

以下代码使用一个包含对象的数组来重新创建一个格式化后的数组。

  1. var kvArray = [{key: 1, value: 10},
  2. {key: 2, value: 20},
  3. {key: 3, value: 30}];
  4. var reformattedArray = kvArray.map(function(obj) {
  5. var rObj = {};
  6. rObj[obj.key] = obj.value;
  7. return rObj;
  8. });
  9. // reformattedArray 数组为: [{1: 10}, {2: 20}, {3: 30}],
  10. // kvArray 数组未被修改:
  11. // [{key: 1, value: 10},
  12. // {key: 2, value: 20},
  13. // {key: 3, value: 30}]

reduce

**reduce()** 方法对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。

  1. arr.reduce(callback(accumulator, currentValue[, index[, array]])[, initialValue])
  2. const array1 = [1, 2, 3, 4];
  3. const reducer = (accumulator, currentValue) => accumulator + currentValue;
  4. // 1 + 2 + 3 + 4
  5. console.log(array1.reduce(reducer));
  6. // expected output: 10
  7. // 5 + 1 + 2 + 3 + 4
  8. console.log(array1.reduce(reducer, 5));
  9. // expected output: 15
  10. // 后面的5表示reducer的初始值

reducer 函数接收4个参数:

  1. Accumulator (acc) (累计器)
  2. Current Value (cur) (当前值)
  3. Current Index (idx) (当前索引)
  4. Source Array (src) (源数组)

reverse

**reverse()** 方法将数组中元素的位置颠倒,并返回该数组。数组的第一个元素会变成最后一个,数组的最后一个元素变成第一个。该方法会改变原数组。

  1. arr.reverse();
  2. const array1 = ['one', 'two', 'three'];
  3. console.log('array1:', array1);
  4. // expected output: "array1:" Array ["one", "two", "three"]
  5. const reversed = array1.reverse();
  6. console.log('reversed:', reversed);
  7. // expected output: "reversed:" Array ["three", "two", "one"]
  8. // Careful: reverse is destructive -- it changes the original array.
  9. console.log('array1:', array1);
  10. // expected output: "array1:" Array ["three", "two", "one"]

some

**some()** 方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。

  1. arr.some(callback(element[, index[, array]])[, thisArg])
  2. const array = [1, 2, 3, 4, 5];
  3. // checks whether an element is even
  4. const even = (element) => element % 2 === 0;
  5. console.log(array.some(even));
  6. // expected output: true

示例

  • 测试数组元素的值

下面的例子检测在数组中是否有元素大于 10。

  1. function isBiggerThan10(element, index, array) {
  2. return element > 10;
  3. }
  4. [2, 5, 8, 1, 4].some(isBiggerThan10); // false
  5. [12, 5, 8, 1, 4].some(isBiggerThan10); // true
  • 使用箭头函数测试数组元素的值

箭头函数 可以通过更简洁的语法实现相同的用例.

  1. [2, 5, 8, 1, 4].some(x => x > 10); // false
  2. [12, 5, 8, 1, 4].some(x => x > 10); // true
  • 判断数组元素中是否存在某个值

此例中为模仿 includes() 方法, 若元素在数组中存在, 则回调函数返回值为 true :

  1. var fruits = ['apple', 'banana', 'mango', 'guava'];
  2. function checkAvailability(arr, val) {
  3. return arr.some(function(arrVal) {
  4. return val === arrVal;
  5. });
  6. }
  7. checkAvailability(fruits, 'kela'); // false
  8. checkAvailability(fruits, 'banana'); // true
  • 使用箭头函数判断数组元素中是否存在某个值
  1. var fruits = ['apple', 'banana', 'mango', 'guava'];
  2. function checkAvailability(arr, val) {
  3. return arr.some(arrVal => val === arrVal);
  4. }
  5. checkAvailability(fruits, 'kela'); // false
  6. checkAvailability(fruits, 'banana'); // true
  • 将任意值转换为布尔类型
  1. var TRUTHY_VALUES = [true, 'true', 1];
  2. function getBoolean(value) {
  3. 'use strict';
  4. if (typeof value === 'string') {
  5. value = value.toLowerCase().trim();
  6. }
  7. return TRUTHY_VALUES.some(function(t) {
  8. return t === value;
  9. });
  10. }
  11. getBoolean(false); // false
  12. getBoolean('false'); // false
  13. getBoolean(1); // true
  14. getBoolean('true'); // true

filter

**filter()** 方法创建一个新数组, 其包含通过所提供函数实现的测试的所有元素。

  1. var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])
  2. const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
  3. const result = words.filter(word => word.length > 6);
  4. console.log(result);
  5. // expected output: Array ["exuberant", "destruction", "present"]

示例

  • 筛选排除所有较小的值

下例使用 filter 创建了一个新数组,该数组的元素由原数组中值大于 10 的元素组成。

  1. function isBigEnough(element) {
  2. return element >= 10;
  3. }
  4. var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
  5. // filtered is [12, 130, 44]
  • 过滤 JSON 中的无效条目

以下示例使用 filter() 创建具有非零 id 的元素的 json。

  1. var arr = [
  2. { id: 15 },
  3. { id: -1 },
  4. { id: 0 },
  5. { id: 3 },
  6. { id: 12.2 },
  7. { },
  8. { id: null },
  9. { id: NaN },
  10. { id: 'undefined' }
  11. ];
  12. var invalidEntries = 0;
  13. function isNumber(obj) {
  14. return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
  15. }
  16. function filterByID(item) {
  17. if (isNumber(item.id) && item.id !== 0) {
  18. return true;
  19. }
  20. invalidEntries++;
  21. return false;
  22. }
  23. var arrByID = arr.filter(filterByID);
  24. console.log('Filtered Array\n', arrByID);
  25. // Filtered Array
  26. // [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
  27. console.log('Number of Invalid Entries = ', invalidEntries);
  28. // Number of Invalid Entries = 5
  • 在数组中搜索

下例使用 filter() 根据搜索条件来过滤数组内容。

  1. var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
  2. /**
  3. * Array filters items based on search criteria (query)
  4. */
  5. function filterItems(query) {
  6. return fruits.filter(function(el) {
  7. return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
  8. })
  9. }
  10. console.log(filterItems('ap')); // ['apple', 'grapes']
  11. console.log(filterItems('an')); // ['banana', 'mango', 'orange']

ES2015 实现

  1. const fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
  2. /**
  3. * Array filters items based on search criteria (query)
  4. */
  5. const filterItems = (query) => {
  6. return fruits.filter((el) =>
  7. el.toLowerCase().indexOf(query.toLowerCase()) > -1
  8. );
  9. }
  10. console.log(filterItems('ap')); // ['apple', 'grapes']
  11. console.log(filterItems('an')); // ['banana', 'mango', 'orange']