当前位置:网站首页>Common skills of JS code
Common skills of JS code
2022-06-10 06:16:00 【ysds20211402】
from : Micro reading https://www.weidianyuedu.com
1. Avoid chain declarations
consequence : Global variables may be introduced
// The wrong way to write var a = b = 0;
In this code ,b Actually declared as a global variable . Because the operator priority is from right to left , So this statement is equivalent to :
var a = (b = 0)
here b Directly assigned without declaration , therefore b It becomes a global variable
2. A single var principle
This rule means , Put all the variables inside the function , Put it at the top and declare . such as :
// Example function A(){ var a = 1, b = 2, c = a + b ; }
advantage :
Easy to find local variables used inside the function
Prevent variables from being used when they are undefined
Prevent misunderstanding caused by variable declaration Promotion
On the third point , Here is an example to illustrate :
var x = 1; function A(){ console.log(x);// The first output , Pay attention to the results var x = 2; console.log(x);// Second output 2, That's all right. }
From the code point of view , The second output must be ok , Some people may think that the first output is 1, Because there is no variable declared inside the function at this time x, According to the scope chain , If you look into the outer layer ,x The value is 1. But the actual output value should be undefined, because js Allow variables to be declared anywhere in a function , And declaring anywhere is the same as declaring at the top , This is the declaration of ascension . So the code above is equivalent to :
var x = 1; function A(){ var x;// Lift to the top console.log(x);// At this time, it has been declared that Unassigned x = 2;// assignment console.log(x); }
3. Use for loop , Cache length value
Usually used for Loop through the array , I can write in the following way :
for(var i = 0;i
The problem with this code is , In each iteration step , Must visit once arr The length of . If arr It's a static value , But we're using js You may encounter arr yes dom Element object , because dom Under the object loading page is the active query , This length query is quite time-consuming ,
// use len Cache length value for(var i = 0,len = arr.length;i
According to the code above , We cache the length value the first time we get it , The above problems can be avoided .
4. Use for-in when , increase hasOwnProperty() Judge
for-in It is usually used to enumerate the properties and methods of objects , However, this method will enumerate the scope, including the object and the prototype object of the object ( For those who don't understand the prototype object, please see the article portal I wrote before ) here , utilize hasOwnProperty() Methods can help us filter out properties and methods that are only on the object itself , Or only in the properties and methods of the prototype chain
for(var key in obj){ if(obj.hasOwnProperty(key)){ // The properties or methods of the object itself } else{ // Properties and methods of prototype chain }}/* Here is a concrete example */ function A(name){ this.type = "A class "; this.name = name || " unnamed "}var a = new A("a");function B(name){ this.subtype = "B class ";}// Build a prototype chain B.prototype = a;B.prototype.sayHello = function(){}var b = new B();// Traversal properties for(var key in b){ // Object properties if(b.hasOwnProperty(key)){ console.log(" Properties or methods of the object itself :"+key) } // Another way to write the above expression if(B.prototype.hasOwnProperty.call(b,key)){ console.log(" Properties or methods of the object itself :"+key) } else { console.log(" Properties or methods of prototype chain :"+key) }}
5. Use === Instead of ==
This is quite common , because js When making comparative judgments , Will cast , such as false == 0 return true In this case , Use === Strict equivalence comparison can be performed , Easier to read code ( Later readers don't need to judge whether this is missing or deliberately using cast shorthand )
6. Use parseInt() when , Take the second parameter .
parseInt() Used to get a numeric value from a string , The second parameter represents the base , The default is 10. We may habitually ignore this parameter when using , But in some cases there will be problems : When the beginning of the string is 0 when , stay es3 It will be treated as octal ,es5 It's still as 10 Base number , For code consistency and avoiding unnecessary mistakes , You should bring parameters with you every time you use them :
var x = parseInt("089",10);// Use with hexadecimal parameters
7. The use of braces
The use of braces is mainly 2 In terms of :
The first 1, Don't omit braces , Even if you can ignore , such as :
for(var i =1;i
There is no problem with the above statement , But if other statements are added to the function body later , It's easy to forget to fill in braces , Therefore, it is recommended to put curly braces ;
The first 2, The of braces must be on the same line as the previous statement
Why is this place thickened ? Because this problem is very easy to ignore , Usually we think it's just a matter of habit whether curly braces are on the same line or the next line of the statement , But actually not ! Here's an example :
function func(){ return { name:"xxx" }}var res = func()console.log(res)// Output undefined
Do you think it's strange , Looking at the code, the first feeling should be to output a containing name Object of property . Please note that , because js The semicolon insertion mechanism of : If the statement does not end with a semicolon , Will automatically add semicolons , Therefore, the above code is actually equivalent to the following writing method :
function func(){ return undefined;// Insert semicolon automatically { name:"xxx" }}
The correct way of writing should be :
function func(){ return { name:"xxx" }}var res = func()console.log(res)// Output {name:"xxx"}
边栏推荐
- 李宏毅老师《机器学习》课程笔记-4.2 Batch Normalization
- How to convert text into numerical value in excel?
- 常用字符串输入流整理(gets()、fgets、getline()、cin.get()、cin.getline())
- Flink 系例 之 CountWindowAll
- Idea plug-in recommendation: file tree enhancement, displaying class comments
- What to say and what not to say during the interview - May 23, 2022
- Machine learning notes - Interpretation of transformer/attention papers
- Transformer XL model details
- QT upper computer controls ABB in real time through EGM
- 反向域名解析是什么?
猜你喜欢
Solution to the frequency limit of 2400 in the 7000p memory

Several skills of API interface optimization

李宏毅老师《机器学习》课程笔记-4.2 Batch Normalization

ArcGIS application (XVIII) detailed explanation of display accuracy change of ArcGIS vector layer attribute table

WireShark抓包分析

How much does it cost to develop a software application?

火狐浏览器设置指向代理模式

Analyse de la capture de paquets wireshark

SQL practice: SQL foundation and execution sequence

Firefox browser settings point to proxy mode
随机推荐
Transformer XL model details
jacoco精确到行整理
What does IP address 0.0.0.0 mean?
CANape XCP on CAN工程创建
ECMAScript 6 syntax addition (shorthand)
ArcGIS应用(十九)Arcgis 统计分析计算多波段图像最大值、最小值、平均值等
Working with MySQL databases in a project
SQL practice: SQL solves problems for X consecutive days
Fix a button in the lower right corner
Countwindowall of Flink
Flink 系例 之 Watermarks
树莓派4B编译内核模块
Time complexity and space complexity
SZT Mr message middleware is easy to use
基于模型的多智能体强化学习中的模型学习理解
常用字符串输入流整理(gets()、fgets、getline()、cin.get()、cin.getline())
Teacher lihongyi's notes on machine learning -4.2 batch normalization
Business topic: channel flow analysis
火狐浏览器设置指向代理模式
Business topic: ab test experiment design and evaluation