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.
[Related recommendations: javascript video tutorial, web front-end】
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); }, };}
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 timer
Will not be cleared by the JS
garbage collection mechanism (will resist permanently in memory, even if the count
function is destroyed), this is what can be done in External call cancel
Cleartimer
The 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).
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
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;}
implements the function makeClosures
, and meets the following conditions after calling:
1. Returns a function array result
, length Same as arr
2. Run the i
th 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
Solution:
function makeClosures(arr, fn) { const result = [] arr.forEach(item=>{ result.push(function(){ return fn(item) }) }) return result}
This question may seem confusing at first glance, but you It is easy to find the solution by combing from top to bottom:
makeClosures
Return an arrayfn
using the corresponding elements in arr
as parametersFunctionuseArguments
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
Solution:
function useArguments() { return [...arguments].reduce((a, b) => a + b);}
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)
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) }}
第一个arr
数组表示的是partialUsingArguments
接收的第一个参数之后的全部参数数组。
因为arguments
是伪数组,不具有slice
方法,所以这里通过随便一个数组(我选的是空数组[]
)来调用slice
,然后通过call
修改调用的这个slice
的this
指向,使其指向到arguments
,这样就相当于是在arguments
上使用slice
方法。
call
修改函数this
指向并立即调用该函数,call
第一个参数表示需要修改的this
指向,之后的所有参数都会作为原函数的参数传递到原函数中。
slice(begin,end)
方法能切割数组,返回一个新的数组对象,这一对象是一个由begin
和end
决定的原数组的浅拷贝(包括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!