(6)find(返回查找到的元素、回调函数返回布尔值)
(返回查找到的元素、回调函数返回布尔值,只要为true,循环就停止,返回当前项)查找数组中符合条件的第一个元素,并返回该元素。如果找不到符合条件的元素,则返回undefined。
const numbers = [1, 2, 3, 4, 5];
// 查找大于3的第一个元素
const result = numbers.find((element) => element > 3);
console.log(result); // 输出: 4
const students = [
{ name: '张三', age: 18 },
{ name: '李四', age: 20 },
{ name: '王五', age: 22 }
];
// 查找年龄大于20的第一个元素
const result = students.find((element) => element.age > 20);
console.log(result);
// 输出: { name: "王五", age: 22 }
(7)reduce(给入一个初始值,后续操作都在给这个初始值做修饰。)
(eg:给入对象最终返回对象、给入数组最终返回数组、给入字符串最终返回字符串)
reduce会循环数组每一项,并且会保留上一次循环的结果 供 下一次循环使用,最终结果为数组循环完毕后的最终返回的(return值) array.reduce(reducer[, 2]) reducer是一个函数,接收四个参数:
accumulator:累加器,初始值等于 initialValue 或者数组的第一个元素(如果没有提供 initialValue)。
currentValue:当前元素的值。
currentIndex:当前元素的索引。
array:原始数组。
initialValue 是可选的,用于指定累加器的初始值。如果没有提供初始值,则累加器的初始值为数组的第一个元素,此时 reducer 函数会从数组的第二个元素开始。
const arr = [1, 2, 3, 4, 5];
const sum = arr.reduce((accumulator, currentValue) => accumulator + currentValue);
console.log(sum); // 输出:15
使用reduce方法实现查找年龄大于等于20的元素:
const students = [
{ name: '张三', age: 18 },
{ name: '李四', age: 20 },
{ name: '王五', age: 22 }
];
const arr1 = students.reduce((pre, cur) => {
if (cur.age >= 20) {
pre.push(cur);
}
return pre
}, [])
console.log(arr1);
//[ { name: '李四', age: 20 }, { name: '王五', age: 22 } ]
(8)reverse(会改变原数组,返回值是数组)
反转数组,会改变原数
const arr = [1,2,3,4,5];
arr.reverse();
console.log(arr); //[5,4,3,2,1]
(9)concat(返回新数组,不会修改原数组)
将两个或多个数组合并成一个新数组。返回新数组,不会修改原数组。
const array1 = [1, 2, 3];
const array2 = [4, 5, 6];
const array3 = [7, 8, 9];
const newArray = array1.concat(array2, array3);
console.log(newArray);
// [1, 2, 3, 4, 5, 6, 7, 8, 9];
//使用展开运算符实现 contat 合并上面数组的效果
const newarr = [...array1,...array2,...array3]
(10)join(返回字符串)
将数组中的所有元素连接成一个字符串,并返回字符串。 join方法可以接受一个可选的参数,作为连接字符串的分隔符。如果不提供分隔符参数,则默认使用逗号作为分隔符。
const numbers = [1, 2, 3, 4, 5];
const result = numbers.join("-");
console.log(result);
// 结果为 "1-2-3-4-5"