JavaScript——实现一些常用函数

2021/9/12 9:04:49

本文主要是介绍JavaScript——实现一些常用函数,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!

前言

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

内容

forEach

/**
 * 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

/**
 * 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

/**
 * 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

/**
 * 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

/**
 * 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

/**
 * 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

/**
 * 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);


这篇关于JavaScript——实现一些常用函数的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程