我报名参加金石计划1期挑战——瓜分10万奖池,这是我的第1篇文章,点击查看活动详情
本文承接上一篇文章,继续梳理关于数组的一些常用的api。。。
11. every
every()方法测试数组中的所有元素是否通过提供的函数实现的测试。它返回一个布尔值。
array.every(callback[, self])
const isBelowThreshold = currentValue => currentValue < 40
const array = [1, 30, 39, 29, 10, 13]
console.log(array.every(isBelowThreshold))
// output: true
12. filter
filter()方法过滤到给定数组中通过所提供函数实现的测试元素。
array.filter(callback[, self])
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6)
console.log(result)
// output: ['exuberant', 'destruction', 'present']
13. indexOf
indexOf()方法返回可以在数组中找到给定元素的第一个索引,如果不存在则返回-1。
array.indexOf(searchElment [, 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 array = [1, 2, 3, 4]
const initialValue = 0
const sum = array.reduce((pre, cur) => pre + cur, initialValue)
15. reverse
reverse()方法将数组反转并返回对同一数组的引用,第一个数组元素现在成为最后一个,最后一个数组元素成为第一个。换句话说,数组中的元素顺序将转向与前面所述相反的方向;
array.reverse()
const array1 = ['one', 'two', 'three'];
console.log('array1:', array1);
// output: ['one', 'two', 'three']
const reversed = array1.reverse()
console.log('reversed:', reversed);
// output: "reversed:" ["three", "two", "one"]
16. sort
sort() 方法对数组的元素进行就地排序,并返回对同一个数组的引用,该数组现在已排序。默认排序顺序是升序,将元素转换为字符串,然后比较他们UTF-16代码单元值序列。
array.sort(compareFunc)
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
console.log(months);
// output: ["Dec", "Feb", "Jan", "March"]
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
console.log(array1);
// output: [1, 100000, 21, 30, 4]
17. 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"
18. find
find() 方法返回提供的数组中满足提供的测试功能的第一个元素。如果没有值满足测试函数,则返回 undefined。
array.find(function(currentValue, index, arr),self)
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
19. some
some() 方法测试数组中的至少一个元素是否通过了提供的函数实现的测试。如果在数组中找到所提供函数为其返回 true 的元素,则返回 true;否则返回false。它不会修改数组。
array.some(callback[, self]);
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
end!