Home > Web Front-end > JS Tutorial > Examples of five commonly used JavaScript functions (summary sharing)

Examples of five commonly used JavaScript functions (summary sharing)

WBOY
Release: 2022-10-01 08:00:26
forward
2178 people have browsed it

This article brings you relevant knowledge about JavaScript, which mainly introduces five common functions and their examples, including timers, process control, closure application, and arguments remaining parameters As well as related issues of secondary encapsulation functions, let’s take a look at them below. I hope it will be helpful to everyone.

Examples of five commonly used JavaScript functions (summary sharing)

[Related recommendations: javascript video tutorial, web front-end

1. Timer

To implement a dotting timer, the requirements are:

1. From start to end (including start and end ), every 100 milliseconds console.log A number, each number increments by 1

2. The returned object needs to contain a cancel method , used to stop timing operations

3. The first number needs to be output immediately

function count(start, end) {
    console.log(start++); 
    let timer = setInterval(() => {
        if (start <= end) {
            console.log(start++);
        }
    }, 100);
    return {
        cancel: () => {
            clearInterval(timer);
        },
    };}
Copy after login

The first number needs to be output immediately,console.log(start) Mediumstart is to output first and then add 1.

After that, use setInterval timer, count function return out cancel, inside cancel It is an operation to clear the timer (referring to the timer variable declared in the count function). The knowledge of closure is used here.

cancel is a closure function that can access the variable timer in the count function. At this time, this timerWill not be cleared by the JSgarbage collection mechanism (will resist permanently in memory, even if the count function is destroyed), this is what can be done in External call cancelCleartimerThe reason for this timer.

A closure refers to a function that has access to local variables in the scope of another function. A function declared within a function is called a closure function. And the inner function can always access the parameters and variables declared in the outer function in which it is located, even after its outer function is returned (end of life).

2. Process control

ImplementationfizzBuzz function, the relationship between parameters num and return value is as follows:
1. If num can be divisible by 3 and 5 at the same time, return the string fizzbuzz
2. If num can be divisible by 3, return the string fizz
3. If num is divisible by 5, return the string buzz
4. If the parameter is empty or not of Number type , return false
5. In other cases, return parameters num

Example:

输入:15输出:fizzbuzz
Copy after login

This is a simple branch judgment:

function fizzBuzz(num) {
    if (!num || typeof num !== "number") return false;
    
    if (num % 3 === 0 && num % 5 === 0) return "fizzbuzz";

    if (num % 3 === 0) return "fizz";

    if (num % 5 === 0) return "buzz";

    return num;}
Copy after login

3. Closure application

implements the function makeClosures, and meets the following conditions after calling:
1. Returns a function array result, length Same as arr
2. Run the ith function in result, that is, result[i](), the result is the same as fn(arr[i]) Same

Example:

var arr = [1, 2, 3];var fn = function (x) {
    return x * x;};var result = makeClosures(arr, fn);result[1]() === fn(arr[1]) ? console.log("yes") === 4 : console.log("no"); // yes
Copy after login

Solution:

function makeClosures(arr, fn) {
    const result = []
    arr.forEach(item=>{
        result.push(function(){
            return fn(item)
        })
    })
    return result}
Copy after login

This question may seem confusing at first glance, but you It is easy to find the solution by combing from top to bottom:

  • makeClosuresReturn an array
  • Each element in the array is a function
  • And the execution results of these functions must be consistent with the results of calling fn using the corresponding elements in arr as parameters

4. ArgumentsRemaining parameters

FunctionuseArguments can receive 1 or more parameters. Please implement function useArguments to return the result of adding all calling parameters. The test parameters of this question are all of type Number, and there is no need to consider parameter conversion.

输入:1, 2, 3, 4输出:10
Copy after login

Solution:

function useArguments() {
    return [...arguments].reduce((a, b) => a + b);}
Copy after login

The function can directly access the arguments variable. This variable is a pseudo array containing all the parameters received by the function. (Not all methods of arrays).

So I first used ... destructuring to convert arguments into a real array, and then called the array's reduce to sum. method to perform summation. The

reduce() method sequentially executes a reducer function provided by you on each element in the array, each time it runs reducer The calculation results of previous elements are passed in as parameters, and finally the results are summarized into a single return value.

Array.prototype.reduce(callbackFn, initialValue)
Copy after login

Parameters:

  • callbackFn
    A "reducer" function, including Four parameters:

    • previousValue:上一次调用 callbackFn 时的返回值。在第一次调用时,若指定了初始值 initialValue,其值则为 initialValue,否则为数组索引为 0 的元素 array[0]
    • currentValue:数组中正在处理的元素。在第一次调用时,若指定了初始值 initialValue,其值则为数组索引为 0 的元素 array[0],否则为 array[1]
    • currentIndex:数组中正在处理的元素的索引。若指定了初始值
    • initialValue,则起始索引号为 0,否则从索引 1 起始。
    • array:用于遍历的数组。
  • initialValue 可选
    作为第一次调用 callback 函数时参数 previousValue 的值。若指定了初始值 initialValue,则 currentValue 则将使用数组第一个元素;否则 previousValue 将使用数组第一个元素,而 currentValue 将使用数组第二个元素。

五、二次封装函数

实现函数 partialUsingArguments,调用之后满足如下条件:
1、返回一个函数 result
2、调用 result 之后,返回的结果与调用函数 fn 的结果一致
3、fn 的调用参数为 partialUsingArguments 的第一个参数之后的全部参数以及 result 的调用参数

解:

function partialUsingArguments(fn) {
  const arr = [].slice.call(arguments,1)
  return function (...arr2) { // ...arr2表示用arr2接收所有参数,arr2是一个数组
      return fn(...arr,...arr2)
  }}
Copy after login

第一个arr数组表示的是partialUsingArguments接收的第一个参数之后的全部参数数组。

因为arguments是伪数组,不具有slice方法,所以这里通过随便一个数组(我选的是空数组[])来调用slice,然后通过call修改调用的这个slicethis指向,使其指向到arguments,这样就相当于是在arguments上使用slice方法。

call修改函数this指向并立即调用该函数,call第一个参数表示需要修改的this指向,之后的所有参数都会作为原函数的参数传递到原函数中。

slice(begin,end) 方法能切割数组,返回一个新的数组对象,这一对象是一个由 beginend 决定的原数组的浅拷贝(包括 begin,不包括end)。原始数组不会被改变。
不加end参数表示从 begin一直切割到最后。

【相关推荐:javascript视频教程web前端

The above is the detailed content of Examples of five commonly used JavaScript functions (summary sharing). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:csdn.net
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template