JavaScript——实现一些常用函数

2024-08-16 14:50:05 浏览数 (1)

前言

如题,实现一些常用的函数,一个小练习;

内容

forEach

代码语言:javascript复制
/**
 * foreach
 * @param {*} array 
 * @param {*} fn 
 */
function forEach(array, fn) {
    for (let index = 0; index < array.length; index  ) {
       fn(array[index]) 
    }
}

// test
let array = [1,2,3,4,5]

forEach(array, function name(params) {
    console.log(params);
})

fliter

代码语言:javascript复制
/**
 * fliter
 * @param {*} array 
 * @param {*} fn 
 * @returns 
 */
function fliter (array, fn) {
    let res = []
    for (let index = 0; index < array.length; index  ) {
       if (fn(array[index])) {
           res.push(array[index])
       }
    }
    return res
}

// test
let arr = [1,2,3,4,5]
let r = fliter(arr, function name(params) {
    return params % 2 === 0
})
console.log(r);

makeFun

代码语言:javascript复制
/**
 * makeFun
 * @param {*} params 
 * @returns 
 */
function makeFn(params) {
    let msg = "hello fn"
    return function name(params) {
        console.log(msg);
    }
}

// test
const fn = makeFn()
fn()

makeFn()()

once

代码语言:javascript复制
/**
 * once
 * @param {*} fn 
 * @returns 
 */
function once(fn) {
    let done = false
    return function name(params) {
        if (!done) {
            done = true
           return fn.apply(this, arguments)
        }
    }
}

// test
let pay = once(function (money) {
    console.log(`支付: ${money}`);
})

pay(5)
pay(4)
pay(3)

map

代码语言:javascript复制
/**
 * map
 * @param {*} array 
 * @param {*} fn 
 * @returns 
 */
const map = (array, fn) => {
    let res = []
    for (const value of array) {
        res.push(fn(value))
    }
    return res
}

// test
let arr = [1,2,3,4]
arr = map(arr, v => v * v )
console.log(arr);

onece

代码语言:javascript复制
/**
 * every
 * @param {*} array 
 * @param {*} fn 
 * @returns 
 */
const every = (array, fn) => {
    let res = []
    for (const value of array) {
        res = fn(value)
        if (!res) {
            break
        }
    }
    return res
}

// test
let arr = [11,12,16, 1]
let r = every(arr, v => v > 10)
console.log(r);

some

代码语言:javascript复制
/**
 * some
 * @param {*} array 
 * @param {*} fn 
 * @returns 
 */
const some = (array, fn) => {
    let res = false
    for (const value of array) {
        res = fn(value)
        if (res) {
            break
        }
    }
    return res
}

let arr = [1, 2, 3, 4]
let r = some(arr, v => v % 2 === 0)
console.log(r);

0 人点赞