Home Web Front-end JS Tutorial 5 common functions in learning JavaScript

5 common functions in learning JavaScript

Sep 12, 2018 pm 05:31 PM
javascript object copy Currying Anti-shake

There are some issues in JavaScript (for example: throttling functions, anti-shake functions, recursive functions, etc.) that are often discussed. This chapter will introduce you to 5 common functions in the process of learning to use JavaScriptz. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

Array flattening

There are many methods for array flattening, but in the end the best method is recursion to achieve a specified depth of flattening Method, so that you will understand the basic routines.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

function flattenDepth(array, depth = 1) {

  let result = []

  array.forEach(item => {

    let d = depth

    if (Array.isArray(item) && d > 0) {

      result.push(...(flattenDepth(item, --d)))

    } else {

      result.push(item)

    }

  })

  return result

}

 

console.log(flattenDepth([1, [2, [3, [4]], 5]])) // [ 1, 2, [ 3, [ 4 ] ], 5 ]

console.log(flattenDepth([1, [2, [3, [4]], 5]], 2)) // [ 1, 2, 3, [ 4 ], 5 ]

console.log(flattenDepth([1, [2, [3, [4]], 5]], 3)) // [ 1, 2, 3, 4, 5 ]

Copy after login

The recursive implementation is very simple and easy to understand, that is, traversing each item. If an item is an array, let the item continue to be called. Depth is specified here as the flattening depth, because this parameter is important for the array. Every item of has a role to play, so it is placed inside the loop.

Currying

Currying of functions has been talked about badly. Everyone has their own understanding and implementation method. In one sentence The explanation is that if there are enough parameters, it will be executed. If there are not enough parameters, a function will be returned. The previous parameters will be stored until there are enough.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

function curry(func) {

  var l = func.length

  return function curried() {

    var args = [].slice.call(arguments)

    if(args.length < l) {

      return function() {

        var argsInner = [].slice.call(arguments)

        return curried.apply(this, args.concat(argsInner))

      }

    } else {

      return func.apply(this, args)

    }

  }

}

 

var f = function(a, b, c) {

  return console.log([a, b, c])

};

 

var curried = curry(f)

curried(1)(2)(3) // => [1, 2, 3]

curried(1, 2)(3) // => [1, 2, 3]

curried(1, 2, 3) // => [1, 2, 3]

Copy after login

It is not difficult to see from the above code that each time the number of parameters is judged, it is compared with the number of curried function parameters. If it is less than the number, it will continue to return to the function, otherwise it will be executed.

Anti-shake

According to my understanding, anti-shake means that no matter how many times you trigger it, it will wait until a period of time you specify after the last trigger. Time is triggered. Following this explanation, write a basic version.

1

2

3

4

5

6

7

8

function debounce(func, wait) {  var timer  return function() {    var context = this

    var args = arguments

    clearTimeout(timer)

    timer = setTimeout(function() {

      func.apply(context, args)

    }, wait)

  }

}

Copy after login

Now there is a requirement that it will be triggered at the beginning and the last time, and it can be configured. First, write a test page to facilitate testing the function. Each time you press the space bar, the number will increase by 1. Test anti-shake and throttling functions.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

<html>

<head>

    <style>

        #container{text-align: center; color: #333; font-size: 30px;}

    </style>

</head>

<body>

    <div id="container"></div>

    <script>

      var count = 1

      var container = document.getElementById(&#39;container&#39;)

      function getUserAction(e) {

        // 空格

        if (e.keyCode === 32) {

          container.innerHTML = count++

        }

      }

      // document.onkeydown = debounce(getUserAction, 1000, false, true)

      document.onkeydown = throttle(getUserAction, 1000, true, true)

      function debounce(func, wait, leading, trailing) {}

      function throttle(func, wait, leading, trailing) {}

    </script>

</body>

</html>

Copy after login

Determine whether the start and end are executed through the two parameters leading and trailing. If leading is true, it will be executed once every time you press space. If trailing is true, the last trigger will be triggered every time you end. implement. Anti-shake function distance, if both are true, pressing space for the first time will add 1, and then pressing space quickly, the getUserAction inside will not be executed at this time, but will be executed after letting go. Add trailing to false , it will not be executed after letting go.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

function debounce(func, wait, leading, trailing) {

  var timer, lastCall = 0, flag = true

  return function() {

    var context = this

    var args = arguments

    var now = + new Date()

    if (now - lastCall < wait) {

      flag = false

      lastCall = now

    } else {

      flag = true

    }

    if (leading && flag) {

      lastCall = now

      return func.apply(context, args)

    }

    if (trailing) {

      clearTimeout(timer)

      timer = setTimeout(function() {

        flag = true

        func.apply(context, args)

      }, wait)

    }

  }

}

Copy after login

Explain, each time the time of the last call is recorded, compare it with the current time. If it is less than the interval, it will not be executed after the first execution. If it is greater than the interval or called after the interval, Then reset the flag and compare it with the basic version above.

Throttling

Throttling means, No matter how it is triggered, it will be executed at the specified interval, the same Give me the basic version.

1

2

3

4

5

6

7

8

9

10

11

12

13

function throttle(func, wait) {

  var timer

  return function() {

    var context = this

    var args = arguments

    if (!timer) {

      timer = setTimeout(function () {

        timer = null

        func.apply(context, args)

      }, wait)

    }

  }

}

Copy after login

It also adds two parameters like the anti-shake function. You can also use the above example to test. In fact, the codes of the two are very similar.

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

function throttle(func, wait, leading, trailing) {  var timer, lastCall = 0, flag = true

  return function() {    var context = this

    var args = arguments

    var now = + new Date()

    flag = now - lastCall > wait    if (leading && flag) {

      lastCall = now      return func.apply(context, args)

    }    if (!timer && trailing && !(flag && leading)) {

      timer = setTimeout(function () {

        timer = null

        lastCall = + new Date()

        func.apply(context, args)

      }, wait)

    } else {

      lastCall = now

    }

  }

}

Copy after login

Object copy

We all know that object copy is divided into deep copy and shallow copy. The black technology method is to use

1

JSON.parse(JSON.stringify(obj))

Copy after login

Another method is to use recursion

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

function clone(value, isDeep) {

  if (value === null) return null

  if (typeof value !== &#39;object&#39;) return value

  if (Array.isArray(value)) {

    if (isDeep) {

      return value.map(item => clone(item, true))

    }

    return [].concat(value)

  } else {

    if (isDeep) {

      var obj = {}

      Object.keys(value).forEach(item => {

        obj[item] = clone(value[item], true)

      })

      return obj

    }

    return { ...value }

  }

}

 

var objects = { c: { &#39;a&#39;: 1, e: [1, {f: 2}] }, d: { &#39;b&#39;: 2 } }

var shallow = clone(objects, true)

console.log(shallow.c.e[1]) // { f: 2 }

console.log(shallow.c === objects.c) // false

console.log(shallow.d === objects.d) // false

console.log(shallow === objects) // false

Copy after login

For basic types, return directly. For reference types, traverse and recursively call the clone method.

Summary

In fact, for the above methods, the general idea is the use of recursion and higher-order functions, including closure The front-end likes to ask these questions about the use of packages. It is best to implement it yourself, which will help understanding.

The above is the detailed content of 5 common functions in learning JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

JavaScript and WebSocket: Building an efficient real-time image processing system JavaScript and WebSocket: Building an efficient real-time image processing system Dec 17, 2023 am 08:41 AM

JavaScript is a programming language widely used in web development, while WebSocket is a network protocol used for real-time communication. Combining the powerful functions of the two, we can create an efficient real-time image processing system. This article will introduce how to implement this system using JavaScript and WebSocket, and provide specific code examples. First, we need to clarify the requirements and goals of the real-time image processing system. Suppose we have a camera device that can collect real-time image data

See all articles