In our work, we can often increase the readability of the code through some small details and make the code look more elegant. This article will share with you some practical JavaScript optimization tips that you can understand at a glance. I hope it will be helpful to you!
「Difficulty:?」 「Recommended reading time: 5min
」
正片
Reduce if...else noodle code
- Once we write more than two
if ...else
function, you should think about whether there is a better optimization method. [Related recommendations: javascript learning tutorial] - For example, if we now need to calculate the price of Mai Lao’s food based on its name, you might do this.
- This way of writing will make the function body have a lot of conditional judgment statements, and when we want to add a product next time, we need to modify the function Adding an
if...else
statement to the internal logic also violates the opening and closing principle to a certain extent. When we need to add a logic, we should try our best to extend the software entity. Address changes in requirements rather than modifying existing code to accomplish changes. - This is a very classic optimization method. We can use an organization's data similar to
Map
to save all products. Here we directly create an object for storage.
- In this way, we don’t need to change the logic of
getPrice
next time we need to add another product. Of course, here is actually More people like to usefoodMap
directly where they are used. I just gave a simple example to express this idea. - Then some classmates will ask, if I don’t want to
key
just use strings, then you can usenew Map
, idea It's almost the same, with an additional entity extended to store changes.
Pipeline operations replace redundant loops
- There is such a list of Mai Lao food
- If you want to find the food that belongs to Set 1, how will you find it?
- The above is the method we often used before. Obviously, if we replace it with
filter
andmap
instead offor
loop, it can not only make The code is more streamlined and the semantics can be made clearer, so that we can see at a glance that the array is firstfiltered
and thenreorganized
.
find replaces the redundant loop
- Still the above example, if we want to use this food object The use of
find
comes into play when searching for specific food in an array based on attribute values.
includes replace redundant loops
- These are similar to the above two details. The function is a built-in function that we do not need to rewrite. Using it skillfully will save a lot of time.
- As we all know, a bowl of Kangfu Laotan pickled cabbage beef noodles contains pickled cabbage, noodles, beef cubes, Cigarette Butt and Foot Skin, then we want to use a function to verify whether there is foot skin in this surface. How can we write it more concisely?
- Similarly, not only Kang Fu’s Pickled Cabbage Beef Noodles can be played like this, all similar ones can be found in the array Operations on specific elements can be called using the
includes
function.
result return value
- We usually struggle with naming the return value variable when writing functions that have return values, or even For some long functions, we do not use variables but directly
return
. This habit is actually bad, because we need to clarify the logic again when we refer to this code next time. - Generally, in a small function, we can use
result
as the return value.
Return early
However, using
result
as the return value above does not apply to all situations. Sometimes we need to end early. Function body to prevent colleagues later from reading redundant programs.In the following example, when our
selectedKey
does not exist, we shouldreturn
immediately, so that we don’t need to continue reading the following code, otherwise we will face For more complex functions, a lot of reading cost will be increased.
Keep the object intact
- Often when we get the data returned by the backend through the request The data will be processed according to some of the attributes. If there are few attributes to be processed, many students will be accustomed to using the first method.
- But in fact, this habit is bad, because when you are not sure whether this function needs to add dependency attributes in the future, you should keep the integrity of the object, as I mentioned in my last article, Learn to embrace change, if
getDocDetail
not only usesicon
andcontent
, but alsotitle
in the future,date
and other attributes, so we might as well pass in the complete object directly, which not only shortens the parameter list but also makes the code more readable.
Smart use of operators
- When we need to create a new variable, sometimes we need to check it When the variable referenced by the value is
null
or undefined, you can use the simple writing method.
Written at the end
- First of all, thank you all for reading this. This time, I will share the article here and summarize it. A few very basic optimization methods, I hope they can help everyone.
[Related video tutorial recommendations: web front-end]
The above is the detailed content of Several practical JavaScript optimization tips worth knowing. For more information, please follow other related articles on the PHP Chinese website!

去掉重复并排序的方法:1、使用“Array.from(new Set(arr))”或者“[…new Set(arr)]”语句,去掉数组中的重复元素,返回去重后的新数组;2、利用sort()对去重数组进行排序,语法“去重数组.sort()”。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于Symbol类型、隐藏属性及全局注册表的相关问题,包括了Symbol类型的描述、Symbol不会隐式转字符串等问题,下面一起来看一下,希望对大家有帮助。

怎么制作文字轮播与图片轮播?大家第一想到的是不是利用js,其实利用纯CSS也能实现文字轮播与图片轮播,下面来看看实现方法,希望对大家有所帮助!

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于对象的构造函数和new操作符,构造函数是所有对象的成员方法中,最早被调用的那个,下面一起来看一下吧,希望对大家有帮助。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于面向对象的相关问题,包括了属性描述符、数据描述符、存取描述符等等内容,下面一起来看一下,希望对大家有帮助。

方法:1、利用“点击元素对象.unbind("click");”方法,该方法可以移除被选元素的事件处理程序;2、利用“点击元素对象.off("click");”方法,该方法可以移除通过on()方法添加的事件处理程序。

本篇文章给大家带来了关于JavaScript的相关知识,其中主要介绍了关于BOM操作的相关问题,包括了window对象的常见事件、JavaScript执行机制等等相关内容,下面一起来看一下,希望对大家有帮助。

foreach不是es6的方法。foreach是es3中一个遍历数组的方法,可以调用数组的每个元素,并将元素传给回调函数进行处理,语法“array.forEach(function(当前元素,索引,数组){...})”;该方法不处理空数组。


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version
Recommended: Win version, supports code prompts!
