filter
- 定义:过滤数组中所有通过测试的值,返回过滤后的新数组;不改变原数组。参数:
@params{callback},回调函数的参数为element
,index
,array
;
@params{this},this指向;
let arr = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']
arr.filter(word => word.length > 6) // ["exuberant", "destruction", "present"]
every
- 定义:测试数组中的每个元素是不是都能通过测试,返回布尔值。参数:
@params{callback},回调函数的参数为element
,index
,array
;
@params{this},this指向; - 如果数组为空,则总是返回 true;
some
- 定义:判断数组中是否至少有1个元素通过测试,返回布尔值。参数为:
@params{callback},回调函数的参数为element
,index
,array
;
@params{this},this指向;
[1, 2, 3, 4, 5].some(item => item % 2 === 0) // true
includes
- 定义: 判断一个数组中是否包含指定值,返回布尔值。参数为:
@params{valueToFind},需要查找的元素值;
@params{fromIndex},开始搜索的索引,默认为0;
const array1 = [1, 2, 3];
array1.includes(2) // true
-
fromIndex
如果为负数则从末尾开始找位置,再顺序查找;
[1, 2, 3].includes(3, -1); // true
- 如果
fromIndex
为负值,且其对应的数组索引 < 0,则整个数组都会被查找;
['a', 'b', 'c'].includes('c', -100); // true
-
fromIndex
>=数组长度,则返回false
;
['a', 'b', 'c'].includes('c', 3); // false
- 注意不能传参回调!不能传参引用类型数据!
indexOf
- 定义: 在数组中查找给定元素第一次出现位置的索引,没有则返回-1。参数:
@params{valueToFind},需要查找的元素值;
@params{fromIndex},开始搜索的索引,默认为0; -
fromIndex
如果为负数则从末尾开始找位置,再顺序查找; - 如果
fromIndex
为负值,且其对应的数组索引 < 0,则整个数组都会被查找; -
fromIndex
>=数组长度,则返回-1;
lastIndexOf
- 定义: 在数组中查找给定元素最后一次出现位置的索引,没有则返回-1。参数:
@params{valueToFind},需要查找的元素值;
@params{fromIndex},开始搜索的索引,默认为数组末尾索引; - 是从后往前查找;
- 如果
fromIndex
为负值,代表起始索引从后往前的偏移,然后还是从后往前查找。如果fromIndex
对应的索引 < 0, 则返回 -1; -
fromIndex
>=数组长度,则整个数组都会被查找;
find
- 定义:寻找数组中满足测试条件的第一个元素的值并返回,没有则返回
undefined
;
@params{callback},回调函数的参数为element
,index
,array
;
@params{this},this指向;
findIndex
- 定义:寻找数组中满足测试条件的第一个元素的索引并返回,没有则返回
-1
;
@params{callback},回调函数的参数为element
,index
,array
;
@params{this},this指向;
at
- 定义:可以传入正负整数作为索引,返回数组中对应的元素,如果索引为负数,则从后向前取;
- 与
index
的区别,不需要知道数组长度,方便逆向取值;
const array = [5, 12, 8, 130, 44];
let index = 2;
array.at(index) = 8;
index = -2;
array.at(index) = 130;