let arr = [11, 22, 33, 44, 55, 66, 77, 88, 99]
console.log('----------1.手写filter()方法------------');
1. filter()方法,用于过滤数组中的元素,返回过滤结果
function filter(arr, callback) {
let arr1 = [ ]
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
arr1.push(arr[i])
}
}
return arr1
}
let newfilter = filter(arr, item => item % 2 !== 0);
console.log(newfilter);
console.log('----------2.手写find()方法------------');
2.find()方法,用于获取数组中满足规则的第一个元素3
function find(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
return arr[i]
}
}
}
let newfind = find(arr, item => item % 2 === 0)
console.log(newfind);
console.log('----------3.手写findIndex()方法------------');
3.findIndex()方法,用于获取数组中满足规则的第一个元素下标
function findIndex(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
return i
}
}
return -1
}
let newfindIndex = findIndex(arr, item => item % 2 === 0)
console.log(newfindIndex);
console.log('----------4.手写some()方法------------');
4.some()方法,用于表示数组中是否有满足指定规则的元素,有返回true,一个都没有返回false
function some(arr, callback) {
for (let i = 0; i < arr.length; i++) {
if (callback(arr[i])) {
return true
}
}
return false
}
let newsome = some(arr, item => item % 2 === 0)
console.log(newsome);
console.log('----------5.手写map()方法------------');
5.map()方法,用于将原始数组里面的数据根据指定的规则返回新的数组
function map(arr, callback) {
let arr1 = []
for (let i = 0; i < arr.length; i++) {
arr1.push(callback(arr[i]))
}
return arr1
}
let newmap = map(arr, val => val - 2)
console.log(newmap);
console.log('----------6.sort()方法------------');
6.sort()方法,对数组的元素进行排序
function sort(arr, callback) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = 0; j < arr.length - 1 - i; j++) {
if (callback(arr[j], arr[j + 1])) {
let item = arr[j]
arr[j] = arr[j + 1]
arr[j + 1] = item
}
}
}
}
sort(arr, (a, b) => (a - b))
console.log(arr);
sort(arr, (a, b) => (b - a))
console.log(arr);
console.log('----------7.reduceRight()方法------------');
7. reduceRight()方法,统计数组中元素的值(从右到左)
function reduceRight(arr, callback, initNum) {
for (let i = arr.length - 1; i >= 0; i--) {
let r = callback(initNum, arr[i])
initNum = r
}
return initNum
}
console.log(reduceRight(arr, (a, b) => a + b, 0));