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?

零下一度
Release: 2017-07-21 09:33:18
Original
1190 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template