JS数组方法的对比

270 阅读13分钟

对比

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

concat

用于连接两个或多个数组,方法不改变现有数组,执行完成后返回一个新的数组

arr1.caoncat(arr2, arr3, ……, arrx);

参数

参数描述
arr1, arr2 ……, arrx必须,参数可以是具体的值,也可以是数组对象,数量不限

返回值

Type描述
数组对象返回一个新的数组

实例

const res = [1].concat([2], 3, [-1, 10]);
// res -> [1, 2, 3, -1, 10]

copyWith

用于从数组的指定位置拷贝元素到数组的另一个指定位置中。

arr.copyWithin(target, start, end);

菜鸟教程-数组copyWithin

参数

参数默认值描述
target-必需。复制到指定目标索引位置
start-可选。元素复制的起始位置
endarray.length可选。如果为负数,表示倒数

实例

const color = ['red', 'green', 'orange', 'blue'];
color.copyWithin(2, 0); // ['red', 'green', 'red', 'green']
// 等价于
color.copyWithin(2, 0, 4);

entries

返回一个数组的迭代对象,该对象包含数组的键值对,迭代对象中数组的索引值作为key,数组元素作为value。

arr.entries();

菜鸟教程-数组entries

实例

const arr = [Symbol(9), 1, 'test', null, undefined, 'end'];
arr[7] = 'ki';
const iterator = arr.entries();

执行结果如下 image.png

every

用于监测数组所有函数是否都符合指定条件。
如果数组中有一个元素不满足,则整个表达式返回false;如果都满足条件,则返回true

不检测空数组(空数组直接返回true),不改变原数组。
菜鸟教程-数组every

参数

参数描述默认
function(curValue, index, arr)必须,函数,数组中的每个元素都会执行这个函数
thisValue可选,对象作为回调函数时使用,传递给函数undefined

实例

[].every(); //  undefined is not a function
[].every((item) => item !== undefined); // true
[1, 2].every(item => item > 0); // true 
[1, 2].every(item => item > 1); // false

some

用于监测数组中的元素是否有满足指定条件。
如果有一个条件满足条件,则表达式返回true,剩余的元素不会在执行检测。否则则返回false.

不会对空数组进行检测(直接返回false),不改变原数组。

arr.some(function(item, index, arr), this.value);

菜鸟教程-数组some

参数

参数描述默认
function(item, idnex, arr)必须,函数,满足条件的元素都会执行该回调
thisValue可选,对象作为执行回调函数时使用,传递给函数,用做thisundefined

实例

[].some(); // Uncaught TypeError: undefined is not a function
[].some(item => item); // false
[].some(item => item === undefined); // false
[1, 2].some(item => item > 1); // true
[1, 2].some(item => item > 0); // true
[1, 2].some(item => item > 3); // false

fill

将固定值替换数组的元素.
菜鸟教程-数组fill

参数

参数描述默认值
value必须。填充的值-
start必须。开始填充的值-
end可选。停止填充的位置数组长度

实例

const arr = [1, 2, 3, 4];
arr.fill(0);
// [0, 0, 0, 0]

const arr1 = [];
arr1.length = 5;
arr1.fill('ki');
// ['ki', 'ki', 'ki', 'ki', 'ki']

const arr2 = [];
arr2.fill('ki', 0 , 2);
// []

个人觉得第二种用法非常的实用,做业务的时候,就需要将指定元素填充到数组中并固定长度。

filter

创建一个新的数组,新数组中的元素时通过检查指定数组中符合条件的所有元素

注意:不检查空数组,不改变原数组。 菜鸟教程-数组filter

参数

参数描述
function(curValue, index, arr)必须,函数,数组中的每个元素都会执行这个函数
thisValue可选,对象作为改执行函数调函数时使用,传递给函数,省略则为undefined

实例

[].filter(); // Uncaught TypeError: undefined is not a function
[].filter(item => {
    console.log('回调执行');
    return item === undefined; 
}); // 不会打印任何内容,返回空数组
[1, 2, 3].filter(item => item > 1); // [2, 3] 

find

返回满足条件的第一个元素的值。
当数组中的元素在测试条件返回true时,返回符合条件的元素,之后的元素都不会再执行函数。
如果么有满足条件的元素则返回undefined

不检测空数组,不改变原数组 菜鸟教程-数组find

参数

参数描述
functon(curValue, index, arr)必须,在满足条件前之前的元素都会执行
thisValue可选,传递给函数的this值,省略则为undedined

示例

[].find(); // Uncaught SyntaxError: Invalid or unexpected token
[].find(item => {
    console.log('回调函数执行');
    return item > 0;
}); // 回调函数不会执行,不会打印内容
[1, 2, 3].find(item => item > 0); // 1

findIndex

返回第一个满足条件的元素的索引。如果没有符合条件的则返回-1.

空数组不执行回调,不该原数组 菜鸟教程-数组findIndex

参数

参数描述默认
function(curValue, index, arr)必须,符合条件之前的元素都会执行
thisValue可选,回调函数绑定thisundefined

实例

[].findIndex(); // Uncaught SyntaxError: Invalid or unexpected token
[].findIndex(() => {
    console.log(‘回调执行’);
    return true;
}); // 回调不会执行,不会打印任何内容
['12', '123', '123'].findIndex(item => item === '123'); // 回调执行两次,返回结果1

forEach

遍历数组,每个元素都会执行回调

空数组不会执行回调函数 菜鸟教程-数组forEach

参数

参数描述默认
function(curValue, index, arr)必须,数组中的每个元素需要调用的函数
thisValue可选,回调函数的thisundefined

实例

[].forEach(); // Uncaught TypeError: undefined is not a function
[].forEach(() => {
    console.log('回调函数');
}); // 回调函数不会执行,不会打印任何内容
[1, 2, 3].forEach((cur, index) => {
    console(cur, index);
}); // 回调函数回执行3次

from

通过拥有length属性的对象或可选迭代器的对象来返回一个数组。如果对象是数组返回true,否则返回false

Array.from(object, mapFunction, thisValue);

菜鸟教程-数组from

参数

const res = Array.from();
// Uncaught TypeError: undefined is not iterable (cannot read property Symbol(Symbol.iterator))

const res2 = Array.from([1, 2, 3]); // [1 ,2 ,3]
const res3 = Array.from([1, 2], item => item * 2); // [2, 4]
const res4 = Array.from({length: 2}, () => 2); // [2, 2]

const res5 = Array.from({
    '1' : 'test',
    '4': '123',
    'a': 'name1',
    'b': 'nameb',
    length: 5
}, item => item); // [undefined, 'test', undefined, '123']

const res5 = Array.from({
    '1' : 'test',
    '4': '123'
}, item => item); // []

includes

用来判断一个数组是否包含指定的值,如果是返回true,否则false
菜鸟教程-数组includes

参数

参数描述默认
searchValue可选,需要查找的元素值
fromIndex可选,从该索引开始查找,若为负数,则从arr.length + fromIndex开始查找0

实例

[1, 2, 3].includes(2); // true
[1, 2, 3].includes(2, 1); // true 
[1, 2, 3].includes(2, 2); // false
[1, 2, 3].includes(2, -2); // true
[1, 2, NaN].includes(NaN); // true
[undefined].includes(undefined); // true
[undefined].includes(); // true
[].includes(); // false

indexOf

返回数组中某个指定元素的位置(第一个满足条件的)。如果在数组中没有找到指定元素则返回-1
菜鸟教程-数组indexOf

参数

在使用时,item不传也是没有任何报错,所以这儿写的可选

参数描述默认值
item可选undefiend
start可选。合法范围是0 到 arr.length0

实例

[12, 2, 4].indexOf(); // -1
[12, 2, 4, undefined].indexOf(); // 3
[12, 2, 4, NaN].indexOf(NaN); // -1

注意查找NaN,返回的结果是-1

lastIndexOf

返回一个指定的元素在数组中最后出现的位置,从数组的右往左查找。
如果没有查找到,则返回-1
菜鸟教程-数组lastIndexOf

参数

参数描述默认
item可选undefined
start可选默认从元素的最后一位开始

实例

[1, 2, 3, 4, 5].lastIndexOf(5, 3); // -1
[1, 2, 3, 4, 5].lastIndexOf(5, 4); // 4
[12, 2, 4, NaN].lastIndexOf(NaN); // -1

isArray

判断对象是否为数组.
菜鸟教程-数组isArray

参数

参数描述
obj必须,要判断的对象

实例

Array.isArray(123); // false
Array.isArray([]); // true
Array.isArray({}); // false

join

把数组中的所有元素转换成一个字符串

参数

参数描述默认
separator可选,指定要使用的分隔符逗号,

返回值

类型秒速
String返回一个字符串

实例

const arr = [1, 3, 4];
arr.length = 5;
arr.join(); // 1,3,4,,
[1, undefined, null, 4].join(); // 1,,,4

keys

从数组创建一个包含数组值的可迭代对象。
菜鸟教程-数组keys

实例

let arr = [1, 2];
const iterator = arr.keys();

arr.length = 6;
arr[6] = 'ki';
const iterator2 = arr.keys();

实例1执行结果:
image.png

实例2执行结果:
image.png

map

返回一个新数组,数组中的元素为原数组调用函数处理后的值。
按照原是数组元素顺序一次处理元素。

不对空数组进行监测,不会改变元素组(规范使用时) 菜鸟教程-数组map

参数

参数描述默认
function(curValue, index, arr)必须,数组中的每个元素都会执行函数
thisValue可选,传递给回调函数的this指向undefined

实例

const arr = [1, 2, 3];
arr.length = 6;
const res = arr.map(item => item * 2); // [2, 4, 6, empty × 3]

Array.prototype.map.call(12, () => 1); // []
Array.prototype.map.call('12', item => item); // [1, 2]

实现map函数

Array.prototype.kiMap = function(func, thisValue) {
    if(typeof func !== 'function') {
        throw new Error(`${func} is not function`);
    }
    // 当this是字符串 或者 数字时
    const arr = Array.from(this);
    const res = [];
    const len = arr.length;
    for(let i = 0; i < len; i++) {
        if(!arr.hasOwnProperty(i)) continue;
        // 稀松数组
        res[i] = func.call(thisValue, arr[i], i, arr);
    }
    // 解决稀松数组问题
    res.length = len;
    return res;
}
const res = [1, 2].kiMap(item => item * 2);
console.log(res); // [2, 4]

const arr = [1, 2];
arr.length = 6;
const res1 = arr.map(item => item * 2);
const res11 = arr.kiMap(item => item * 2);

pop

删除数组的最后一个元素并返回删除的元素。

改变原数组的长度 菜鸟教程-数组pop

实例

const arr = [1, 2, 3];
const item = arr.pop(); // 3

push

向数组的末尾添加一个或者多个元素,并返回操作后数组的长度

改变原数组,返回值是数组长度 菜鸟教程-数组push

参数

参数描述
item1, item2, …… , itemX必须,要添加数组末尾的元素

实例

const arr = [1, 2, 3];
arr.push(); // 返回 3
arr.push(undefiend); // [1, 2, 3, undefiend], 返回值 4

reduce

接受一个参数作为累加器,数组中的每个值(从左到右)开始累加操作,最终计算为一个值。对与空数组,不会执行回调。

array.reduce(function(total, currentValue, currentIndex, arr), initialValue);

菜鸟教程-数组reduce

实例

// 示例1
[1, 2].reduce((pre, cur, index) => {
    console.log(pre, cur, index)
    return pre + cur
}, 0); // 3

// 示例2
[1, 2].reduce((pre, cur, index) => {
    console.log(pre, cur, index);
    return pre + cur;
})

示例1:返回的结果为3,console输出的是0 1 0 1 2 1
示例2:返回的结果为3, console输出的是1 2 1
从示例1 和 示例2的表现可以看出,当我们没有传入initialValue时,第一次执行回调函数的第一个参数为数组第一个元素,且回调执行的次数会比数组的长度少一次,示例2中的回调只会执行一次。
总结:是否传入初始值,将会影响回调执行的次数

参数

参数描述
function(total, curValue, index, arr)必需,用于执行每个数组元素的函数
initialValue可选,传递给函数的初始值,如果没有传,就默认数组第一个元素

实现reduce函数

Array.prototype.kiReduce = function (func, initailValue) {
    if(typeof func !== 'function') {
        throw new Error(`${func} is not function`);
    }
    const arr = this.slice(0);
    const len = arr.length;
    if(!len && initailValue === undefined) {
        throw new Error('Reduce of empty array with no initial value');
    }
    let pre = initailValue;
    let index = 0;
    if(initailValue === undefined) {
        // 找到第一个非空元素
        for(let i = 0; i < len; i++) {
            if(!arr.hasOwnProperty(i)) continue;
            pre = arr[i];
            index = i;
        }
    }
    for(; index < len; index++) {
        pre = func.call(this, pre, arr[index], index, arr);
    }
    return pre;
}

// 测试
const res1 = [1, 2].kiReduce((pre, cur) => pre + cur); 
const res2 = [1, 2].kiReduce((pre, cur) => pre + cur, 3);  // 6
const res3 = [].reduce(() => {}, 5); // 5
[].kiReduce(); // 20220211.arr.html:13 Uncaught Error: undefined is not function
[].kiReduce(() => {}); // Uncaught Error: Reduce of empty array with no initial value

reduceRight

功能和reduce一样,不同的是reduceRight从数组的末尾向前将数组中的数组想做累加操作。 菜鸟教程-数组reduceRight

参数

参数描述默认
function(total, curValue, index, arr)必须,用于执行每个数组元素的函数
initialValue可选,传递给函数的初始值数组第一个非空元素

实例

[1, 2].reduceRight((pre, cur) => pre + cur); // 返回结果3,回调函数执行1次
[1, 2].reduceRight((pre, cur) => pre + cur, 0); // 返回结果3,回调函数执行2次

reverse

颠倒数组中的元素的顺序。

改变原数组 菜鸟教程-数组reverse

实例

const arr = [1, 2, 3];
arr.reverse();
console.log(arr); // [3, 2, 1]

unshift

向数组的开头添加一个或者更多元素,并返回新的长度

改变原数组的长度 菜鸟教程-数组unshift

实例

const arr = [3, 4, 5];
arr.unshift(0, 1, 2); // [0, 1, 2, 3, 4, 5]

shift

删除数组中的第一个元素,并返回这个元素

改变原数组 菜鸟教程-数组shift

实例

const item = [1, 2, 3].shift(); 
console.log(item); // 1

sort

对数组的元素进行排序。默认按字母升序。

当数子是字母顺序排列时40将排到5前面 菜鸟教程-数组sort

实例

[40, 100, 1, 5, 25, 10].sort(); // 字母升序 [1, 10, 100, 25, 40, 5]
[40, 100, 1, 5, 25, 10].sort((a, b) => a - b); // 数字大小升序 [1, 5, 10, 25, 40, 100]
[40, 100, 1, 5, 25, 10].sort((a, b) => b - a); // 数字大小降序 [100, 40, 25, 10, 5, 1]

slice

从已有的数组中返回选定的元素

不会改变原数组

参数

参数描述
start可选,选取开始位置,若为负数,则表示倒数
end可选,选取结束位置,若为负数,则表示倒数

实例

[1, 2, 3, 4].slice(1, 2); // [2]
[1, 2, 3, 4, 5].slice(-2, -1); // [4]
[1, 2, 3, 4, 5].slice(2, 1); // []

splice

添加或删除数组的元素

改变原数组 菜鸟教程-数组splice

参数

参数描述
index必须。规定从何处添加/删除元素,必须数字,可以为负数
howMany可选,规定应该删除多少元素。必须数字,可以是0。若未传入规定此参数,则删除从index开始到数组结尾的元素
item1, item2, ……, itemX可选,要添加到数组的元素

返回值

type描述
Array如果从数组中删除了元素,则反悔的是含有被删除元素的数组

实例

const arr = [1, 2, 3, 5];
arr.splice(3, 0, 4, 44); 
console.log(arr); // [1, 2, 3, 4, 44, 5]
arr.splice(3, 2); // [4, 44]
console.log(arr); //  [1, 2, 3, 5]

toString

将数组转换为字符串,并返回结果。内部使用的数组的join方法

元素间用逗号分隔 菜鸟教程-数组toString

实例

[1,2].toString(); // '1,2'
const arr = [1, 2];
arr.length = 6;
arr.toString(); // '1,2,,,,'

valueOf

返回数组对象的原始值。

不改变原数组 菜鸟教程-数组valueOf

实例

const arr = [1, 2, 3];
console.log(arr.valueOf()); // [1, 2, 3]
arr.length = 6;
console.log(arr.valueOf()); // [1, 2, 3, empty × 3]
arr[3] = Symbol(3)
console.log(arr.valueOf()); // [1, 2, 3, Symbol(3), empty × 2]

资料

1、菜鸟教程-JavaScript Array 对象