Home Web Front-end JS Tutorial What are the details that need to be paid attention to in Javascript?

What are the details that need to be paid attention to in Javascript?

Jul 21, 2017 am 09:33 AM
javascript js detail

1. Use === instead of ==
JavaScript uses 2 different equality operators: ===|!== and ==|!=, in comparison operations Using the former is best practice.
"If the operands on both sides have the same type and value, === returns true, !== returns false." - JavaScript: Language Essence
However, when using == and! =, you may encounter a situation where the types are different. In this case, the types of the operands will be forced to be the same and then compared, which may not be the result you want.
2.Eval == Evil
When not familiar at first, "eval" gives us access to the JavaScript compiler (Annotation: This seems very powerful). Essentially, we can pass a string to eval as a parameter while executing it.
Not only does this greatly reduce the performance of the script (Annotation: The JIT compiler cannot predict the content of the string and cannot precompile and optimize), but it also brings huge security risks, because the text to be executed is too large. High authority, stay away.

3. Omission may not save trouble
Technically, you can omit most curly braces and semicolons. Most browsers will understand the following code correctly:

if(someVariableExists) 
    x = false
Copy after login

Then, if it looks like this:

if(someVariableExists) 
   x = false 
   anotherFunctionCall();
Copy after login

one might think the above The code is equivalent to the following:

if(someVariableExists) { 
   x = false; 
   anotherFunctionCall(); 
}
Copy after login

Unfortunately, this understanding is wrong. The actual meaning is as follows:

if(someVariableExists) { 
   x = false; 
} 
anotherFunctionCall();
Copy after login

You may have noticed that the indentation above easily gives the illusion of curly braces. Justifiably so, this is a terrible practice and should be avoided at all costs. There is only one case in which the curly braces can be omitted, that is, when there is only one line, but this is controversial.

if(2 + 2 === 4) return 'nicely done';
Copy after login

Plan Ahead
Chances are, one day you will need to add more statements to the if statement block. In this case, you must rewrite this code. Bottom line – omissions are a minefield.

4. Place the script at the bottom of the page
Remember - the primary goal is to make the page presented to the user as quickly as possible. The inclusion of the script is blocking. The browser cannot continue to render the following content until it is loaded and executed. Therefore, users will be forced to wait longer.
If your js is only used to enhance the effect-for example, a button click event-put the script immediately before the end of the body. This is definitely best practice.

5. Avoid declaring variables within a For statement
When executing a lengthy for statement, keep the statement block as concise as possible, for example:
Oops:

for(var i = 0; i < someArray.length; i++) { 
   var container = document.getElementById(&#39;container&#39;); 
   container.innerHtml += &#39;my number: &#39; + i; 
   console.log(i); 
}
Copy after login

Note that each loop must calculate the length of the array, and each time it must traverse the dom to query the "container" element - the efficiency is seriously low!
Suggestion:

var container = document.getElementById(&#39;container&#39;); 
for(var i = 0, len = someArray.length; i < len;  i++) { 
   container.innerHtml += &#39;my number: &#39; + i; 
   console.log(i); 
}
Copy after login


6. The best way to construct a string
When you need to iterate over an array or object, don’t Always think of "for" statements, be creative, you can always find a better way, for example, like below.

var arr = [&#39;item 1&#39;, &#39;item 2&#39;, &#39;item 3&#39;, ...]; 
var list = &#39;<ul><li>' + arr.join('</li><li>') + '</li></ul>';
Copy after login

I am not your god, but please believe me (if you don’t believe it, test it yourself) - this is by far the fastest method!
Using native code (such as join()), regardless of what the system does internally, is usually much faster than non-native.

7. Reduce global variables
As long as multiple global variables are organized under one namespace, it will significantly reduce the interaction with other applications, components or classes. The possibility of bad interaction between libraries "——Douglas Crockford

var name = 'Jeffrey'; 
var lastName = 'Way'; 
function doSomething() {...} 
console.log(name); // Jeffrey -- 或 window.name// 更好的做法var DudeNameSpace = { 
   name : 'Jeffrey', 
   lastName : 'Way', 
   doSomething : function() {...} 
} 
console.log(DudeNameSpace.name); // Jeffrey
Copy after login

Note: This is simply named "DudeNameSpace", which should be more reasonable in practice. name.

8. Add comments to the code
It seems unnecessary, but please believe me, try to add more reasonable comments to your code. When you look back at your project a few months later, you may not remember your original thoughts. Or what if one of your colleagues needs to make changes to your code? All in all, adding comments to your code is an important part.

// 循环数组,输出每项名字(译者注:这样的注释似乎有点多余吧)for(var i = 0, len = array.length; i < len; i++) {
   console.log(array[i]); 
}
Copy after login


9. Embrace progressive enhancement
Ensure smooth degradation when javascript is disabled. We're always tempted to think, "Most of my visitors already have JavaScript enabled, so I don't have to worry." However, this is a big misconception.
Have you ever taken a moment to see what your beautiful page looks like with javascript turned off? (This is easy to do by downloading the Web Developer tool (Translator's Note: Chrome users download it in the app store, IE users set it in Internet Options)), but this may break your website. As a rule of thumb, design your site assuming JavaScript is disabled, and then, based on that, gradually enhance your site.

10. Do not pass string parameters to "setInterval" or "setTimeout"
Consider the following code:

setInterval( 
"document.getElementById(&#39;container&#39;).innerHTML += &#39;My new number: &#39; + i", 3000 );
Copy after login

不仅效率低下,而且这种做法和"eval"如出一辙。从不给setInterval和setTimeout传递字符串作为参数,而是像下面这样传递函数名。

setInterval(someFunction, 3000);
Copy after login

11.不要使用"with"语句
乍一看,"with"语句看起来像一个聪明的主意。基本理念是,它可以为访问深度嵌套对象提供缩写,例如……

with (being.person.man.bodyparts) { 
   arms = true; 
   legs = true; 
}
Copy after login

而不是像下面这样:

being.person.man.bodyparts.arms = true; 
being.person.man.bodyparts.legs= true;
Copy after login

不幸的是,经过测试后,发现这时“设置新成员时表现得非常糟糕。作为代替,您应该使用变量,像下面这样。

var o = being.person.man.bodyparts; 
o.arms = true; 
o.legs = true;
Copy after login

12.使用{}代替 new Ojbect()
在JavaScript中创建对象的方法有多种。可能是传统的方法是使用"new"加构造函数,像下面这样:

ar o = new Object(); 
o.name = &#39;Jeffrey&#39;; 
o.lastName = &#39;Way&#39;; 
o.someFunction = function() { 
   console.log(this.name); 
}
Copy after login

然而,这种方法的受到的诟病不及实际上多。作为代替,我建议你使用更健壮的对象字面量方法。
更好的做法

var o = { 
   name: &#39;Jeffrey&#39;, 
   lastName = &#39;Way&#39;, 
   someFunction : function() { 
      console.log(this.name); 
   } 
};
Copy after login

注意,果你只是想创建一个空对象,{}更好。
13.使用[]代替 new Array()
这同样适用于创建一个新的数组。
例如:

var a = new Array(); 
a[0] = "Joe"; 
a[1] = &#39;Plumber&#39;;// 更好的做法:var a = [&#39;Joe&#39;,&#39;Plumber&#39;];
Copy after login

“javascript程序中常见的错误是在需要对象的时候使用数组,而需要数组的时候却使用对象。规则很简单:当属性名是连续的整数时,你应该使用数组。否则,请使用对象”——Douglas Crockford
14.定义多个变量时,省略var关键字,用逗号代替

var someItem = &#39;some string&#39;; 
var anotherItem = &#39;another string&#39;; 
var oneMoreItem = &#39;one more string&#39;;// 更好的做法var someItem = &#39;some string&#39;, 
    anotherItem = &#39;another string&#39;, 
    oneMoreItem = &#39;one more string&#39;;
Copy after login

应而不言自明。我怀疑这里真的有所提速,但它能是你的代码更清晰。
15.使用Firebug的"timer"功能优化你的代码
在寻找一个快速、简单的方法来确定操作需要多长时间吗?使用Firebug的“timer”功能来记录结果。

function TimeTracker(){ 
 console.time("MyTimer"); 
 for(x=5000; x > 0; x--){} 
 console.timeEnd("MyTimer"); 
}
Copy after login

The above is the detailed content of What are the details that need to be paid attention to in 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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

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.

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

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

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

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

See all articles