数组api总结

307 阅读8分钟

参考: developer.mozilla.org/zh-CN/docs/…

push - 改变数组

添加元素到数组的末尾,返回值数组的长度原数组被改变

var fruits = ['Apple', 'Banana'];
var newLength = fruits.push('Orange');
// newLength:3; 
//fruits: ["Apple", "Banana", "Orange"]

pop - 改变数组

删除数组末尾的元素,返回值是被删除的元素原数组被改变

var fruits = ['Apple', 'Banana'];
var last = fruits.pop(); // remove Orange (from the end)
// last: "Banana"; 
// fruits: ["Apple"];

unshift - 改变数组

添加元素到数组的头部, 返回值数组的长度原数组被改变

var fruits = ['Apple', 'Banana'];
var newLength = fruits.unshift('Strawberry') // add to the front
// newLength:3; 
// ["Strawberry","Apple", "Banana"];

shift - 改变数组

删除数组最前面(头部)的元素,返回值是被删除的元素原数组被改变

var fruits = ['Apple', 'Banana'];
var first = fruits.shift(); // remove Apple from the front
// first: "Apple"; 
// fruits: ["Banana"];

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"]

splice - 改变数组

语法: array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

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

从第 2 位开始删除 0 个元素,插入“drum”

var myFish = ["angel", "clown", "mandarin", "sturgeon"];
var removed = myFish.splice(2, 0, "drum");

// 运算后的 myFish: ["angel", "clown", "drum", "mandarin", "sturgeon"]
// 被删除的元素: [], 没有元素被删除

从第 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"]
// 被删除的元素: [], 没有元素被删除

从第 3 位开始删除 1 个元素

var myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
var removed = myFish.splice(3, 1);

// 运算后的 myFish: ["angel", "clown", "drum", "sturgeon"]
// 被删除的元素: ["mandarin"]

从第 2 位开始删除 1 个元素,插入“trumpet”

var myFish = ['angel', 'clown', 'drum', 'sturgeon'];
var removed = myFish.splice(2, 1, "trumpet");

// 运算后的 myFish: ["angel", "clown", "trumpet", "sturgeon"]
// 被删除的元素: ["drum"]
从第 0 位开始删除 2 个元素,插入"parrot""anemone""blue"
var myFish = ['angel', 'clown', 'trumpet', 'sturgeon'];
var removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');

// 运算后的 myFish: ["parrot", "anemone", "blue", "trumpet", "sturgeon"]
// 被删除的元素: ["angel", "clown"]

从倒数第 2 位开始删除 1 个元素

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(-2, 1);

// 运算后的 myFish: ["angel", "clown", "sturgeon"]
// 被删除的元素: ["mandarin"]

从第 2 位开始删除所有元素

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
var removed = myFish.splice(2);

// 运算后的 myFish: ["angel", "clown"]
// 被删除的元素: ["mandarin", "sturgeon"]

sort - 改变数组

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]

const array1 = [1, 30, 4, 21, 100000];
array1.sort((a,b) => b - a);
console.log(array1);
// expected output: Array [100000, 30, 21, 4, 1]

fill - 改变数组

语法: arr.fill(value[, start[, end]]) 方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。不包括终止索引。

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]

copyWithin - 改变数组

developer.mozilla.org/zh-CN/docs/…

slice

语法: arr.slice([begin[, end]]) 方法返回一个新的数组对象,这一对象是一个由 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"]

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"]

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"

toString

返回一个字符串,表示指定的数组及其元素。

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());
// expected output: "1,2,a,1a"

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

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

includes

方法用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

find

方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined。

const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// expected output: 12

findIndex

方法返回数组中满足提供的测试函数的第一个元素的索引。若没有找到对应元素则返回-1。

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

forEach

forEach() //没有返回值。

//demo
let ary = [12,23,24,42,1];  
let res = ary.forEach(function (item,index,input) {  
    input[index] = item*10;  
})  
console.log(res);//--> undefined;  
console.log(ary);//--> 通过数组索引改变了原数组;//120,230,240,420,10

map和filter有什么区别?

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

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

特点:

  • map 方法会给原数组中的每个元素都按顺序调用一次 callback 函数,callback 每次执行后的 返回值 包括 undefined)组合起来形成一个新数组。 callback 函数只会在有值的索引上被调用;那些从来没被赋过值或者使用 delete 删除的索引则不会被调用。

  • filter 为数组中的每个元素调用一次 callback 函数,并利用所有使得 callback 返回 true 或等价于 true 的值的元素创建一个新数组。callback 只会在已经赋值的索引上被调用,对于那些已经被删除或者从未被赋值的索引不会被调用。那些没有通过 callback 测试的元素会被跳过,不会被包含在新数组中。

const arr2 = new Array(3);
arr2[1] = 90;

let newArray  = arr2.map((item,index) => {
  console.log(item, index, '=======') // 数组length为3,但是打印结果只有一次:90 1 =======
  return item * 2;
});
console.log(arr2, 'arr2',)  // 打印结果:[ <1 empty item>, 90, <1 empty item> ] arr2(原数组没有被改变)
console.log(newArray, 'newArray',) // 打印结果:[ <1 empty item>, 180, <1 empty item> ] newArray (新数组)
const newArrFilter = arr2.filter((a) => {
   console.log(a) // 这里只会执行一次的,打印90
   return a*2;
});
console.log(arr2, 'arr2',)  // 打印结果:[ <1 empty item>, 90, <1 empty item> ] arr2(原数组没有被改变)
console.log(newArrFilter, 'newArrFilter',) // 打印结果:[90] newArray (新数组)

以上参考: blog.csdn.net/qq_40713392…

reduce

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

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));
// expected output: 15

reduceRight

方法接受一个函数作为累加器(accumulator)和数组的每个值(从右到左)将其减少为单个值。

const array1 = [[0, 1], [2, 3], [4, 5]].reduceRight(
  (accumulator, currentValue) => accumulator.concat(currentValue)
);

console.log(array1);
// expected output: Array [4, 5, 2, 3, 0, 1]

some

对数组中的每个元素都执行一次指定的函数(callback),直到此函数返回 true,如果发现这个元素,some 将返回 true,如果回调函数对每个元素执行后都返回 false ,some 将返回 false。它只对数组中的非空元素执行指定的函数,没有赋值或者已经删除的元素将被忽略。

function isBigEnough(element, index, array) {
    return (element >= 10);
}
var passed = [2, 5, 8, 1, 4].some(isBigEnough);
// passed is false
passed = [12, 5, 8, 1, 4].some(isBigEnough);
// passed is true

every

对数组中的每个元素都执行一次指定的函数(callback),直到此函数返回 false,如果发现这个元素,every 将返回 false,如果回调函数对每个元素执行后都返回 true ,every 将返回 true。它只对数组中的非空元素执行指定的函数,没有赋值或者已经删除的元素将被忽略

function isBigEnough(element, index, array) {
    return (element >= 10);
}
var passed = [12, 5, 8, 130, 44].every(isBigEnough);
// passed is false
passed = [12, 54, 18, 130, 44].every(isBigEnough);
// passed is true

entries

方法返回一个新的Array Iterator对象,该对象包含数组中每个索引的键/值对。

const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();
console.log(iterator1);
// expected output: Object {  }
console.log(iterator1.next().value);
// expected output: Array [0, "a"]

console.log(iterator1.next().value);
// expected output: Array [1, "b"]

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

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"

数组相关面试题