Home > Web Front-end > JS Tutorial > Practical use of javascript for beginners

Practical use of javascript for beginners

巴扎黑
Release: 2018-05-16 15:27:44
Original
1192 people have browsed it

1. Prefer using === instead of ==

JavaScript uses two equality operators: ===|!== and ==|!=. It is usually considered the most effective for comparison. Best practice is to use the former set of operators.

"If the two operands have the same type and value, then the result of the === comparison is true, and the result of the !== comparison is false."                                 . JavaScript language essence

However, if you use == and !=, you will run into problems when comparing operands of different types. In this case, this set of operators will try to Useless coercion of the value of a number.

2.Eval is synonymous with bad

For those who are not familiar with JavaScript, the function "evel" gives us access to the JavaScript compiler, We can get the result of the string execution by passing a string parameter to "eval".

This will not only greatly reduce the performance of your script. It will also cause a huge security risk, because this If you have the ability to pass in too much plain text, avoid using the eval function as much as possible. Parentheses and semicolons. Most browsers can correctly save the following code snippet:

if(someVarianbleExists)
x = false
Copy after login

However, consider this code again:

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

Some people may think that the previous code is equivalent Yu:

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

You should have also noticed that the indentation in the code imitates the function of curly braces. Needless to say, this is a very terrible practice and should be avoided at all costs. The only time when curly braces can be omitted is In a one-line statement, but even this situation is very controversial.

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

Always think about the future

If some time in the future, you need to use this if What should you do if you add more commands to the statement? You have no choice but to rewrite this code. The bottom line in dealing with this problem is to be cautious about omitting writing.

4. Use JS Lint

JSLint is a debugger written by Douglas Crockford. Simply copy your script into it and it will quickly solve any obvious problems and errors in your code.

"JSLint takes a copy of the JavaScript source code and scans the code. If a problem is found, a message is returned describing the problem and its approximate location in the source code. The problem, although often a syntax error, is not necessarily a syntax error. JSLint will also look Some style habits and structural issues. It does not prove whether your code is correct, but just provides another pair of eyes to help find problems.

Execute JSLint once before finishing writing the script code. You won't make stupid mistakes.

5. Put the script at the bottom of the page

This tip was also recommended in the previous article in this series, because it is also very useful here. As it's highly appropriate though, I'll paste that information directly here.

Remember - the main goal of this best practice is to load the page as quickly as possible for the user. When loading A script, the browser cannot continue until the entire script file has been loaded. Therefore, the user must wait longer before noticing any progress.

If the purpose of the JS file is only to add functionality-- For example. After clicking a certain button - then put those files at the bottom, before the body closing tag. This is definitely a best practice.

Better practice

<p>And now you know my favorite kinds of corn. </p> <script type="text/javascript" src="path/to/file.js?1.1.11">
</script> <script type="text/javascript" src="path/to/anotherFile.js?1.1.11"></script> </body> </html>
Copy after login

6. Declare variables outside the For statement

When executing a lengthy 'for' statement, just let the interpretation engine do what it must do.

For example:

Bad practice:

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 iteration in the above code snippet needs to check the length of the array. And each time it has to traverse the DOM tree to find the 'container' element - how inefficient!! !

Better approach

ar 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

7. The fastest way to construct a string

When you need to traverse an array or object, don’t always use what you have at your fingertips 'for' statements, be creative and find the fastest solution that gets the job done.

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

"I won't bore you with benchmarks; you just have to trust me (or test it yourself) - this By far the fastest way! ”

Using native methods (such as join()), regardless of what is happening behind the abstraction level, is usually much faster than any non-native method.

8. Reduce global variables

By encapsulating global things into a single namespace, you can greatly reduce the probability of confusing interactions with other applications, components, and code libraries.

 var name = &#39;jeffrey&#39;;
var lastname = &#39;way&#39;;
function doSomething(){...}
console.log()
Copy after login

Better approach

var DudeNameSpace = {
name:&#39;Jeffrey&#39;;
lastname:&#39;way&#39;,
doSometing: function(){...}
}
console.log(DudeNameSpace.name);
Copy after login

9 .Comment your code

It may not seem necessary at first, but trust me, you will want to comment your code as well as possible. When you come back to the project after a few months, what will happen What? Find out that you can't easily explain your original thoughts on each line of code. Or, what if one of your colleagues needs to modify your code? Always, always remember to comment on your code The important part.

10. Embrace Progressive Enhancement

Always consider how to handle situations where JavaScript is disabled. Maybe you’re thinking “most readers of my page have JavaScript enabled, so I'm not worried about this issue. However, this is a huge mistake.

你曾花时间去看过关闭JavaScript后你的漂亮的花动态哦是什么样么?也许他会完全破坏你的站点.按照以往经验,设计你的站点是应假设将会禁用JavaScript,那么,一旦你这样做了,那么开始渐进的增强你的网页布局吧!

11.不要传递字符串给"SetInterval"或"SetTimeout"

考虑一下如下代码:

etInterval( "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

12.不要使用"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.

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

13 使用{}而不是new Object()

JavaScript中有很多种穿件对象的方式.也许更传统的方式是使用''new''构造器.像这样:

var o = new Object(); o.name = 'Jeffrey'; o.lastname = 'Way'; o.someFuncion = function() { console.log(this.name); }

然而,这种方式因其行为并不是我们所想的那样而被认为是"糟糕的实践".相反,我推荐你使用更健壮的对象字面方法.

更好的写法

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

注意如果你只是想简单地创建个空对象,{}就派上用场了.

var o = {};
Copy after login

对象字面量使我们能够编写支持很多特性的代码,并对代码的实现者来说代码仍然相对直观,不需要直接调用构造器或维护传递给函数的参数的正确顺序,等等.

14.使用[]而不是New Array()

这同样适用于创建一个新数组

过去的写法

var a = new Array(); a[0] = &#39;Joe&#39;; a[1] = &#39;Plumber&#39;;
Copy after login

更好的写法 var a = ['Joe', 'Plumber'];

Javascript中一个常见的错误是需要数组时使用对象或需要对象时使用数组,规则很简单:当属姓名是小的连续整数时,你应该使用数组,否则,使用对象

15.一长串变量? 省略''var''关键字,使用逗号替代

var someItem = &#39;some string&#39;; var anotherItem = &#39;another string&#39;; var oneMoreItem = &#39;one more string&#39;;
Copy after login

更好的写法

var someItem = &#39;some string&#39;,     anotherItem = &#39;another string&#39;,     oneMoreItem = &#39;one more string&#39;;
Copy after login

相当的不言自明,我不知道这里是否有任何真正的速度提升,但是它使你的代码更加简洁了.

16.始终,始终使用分号

技术上来说,大多数浏览器都允许你省略一些分号

var someItem = &#39;some string&#39; function doSomething() {     return &#39;something&#39; }
Copy after login

话虽如此,但这是一种非常糟糕的做法,可能导致更大的问题,问题查找起来也更困难

更好的写法

var someItem = &#39;some string&#39;; function doSomething() {     return &#39;something&#39;; }
Copy after login

18.For in 语句

遍历对象内的成员时,你也会得到方法函数,为了解决这个问题,应始终将你的代码包装在一个if语句中来过滤信息

for(key in object) {     if(object.hasOwnProperty(key)) {         ... then do something...     } }
Copy after login

19.使用firebug的''Timer''特性来优化代码

需要一种快速简单地方法来检测一个操作花费多长时间么?

使用Firebug的timer特性记录结果

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

20.读书 面向对象的JavaScript

  • JavaScript:语言精粹

  • 学习jQuery 1.3

  • 学习JavaScript

21.自执行函数(self-executing functions)

相比调用函数,当页面加载或调用父函数时,让函数自动执行会简单些.简单地将你的函数包装在圆括号内,并添加额外的一对圆括号,其本质上就调用了这个函数

(function doSomething() {     return {         name: &#39;jeff&#39;,         lastName: &#39;way&#39;     };  })();
Copy after login

22.原始(raw)javascript代码的执行速度始终快于使用代码库

Javascript代码库,如jQuery和mootools,能够为你节省大量的编码时间--特别是使用ajax操作.话虽如此,适中谨记代码库的执行速度适中是比不上原始JavaScript代码的(假设了代码的正确性)

jQuery的each方法来做遍历非常赞,但使用原生for语句适中会快一些

23.crockford的json.parse

虽然JavaScript 2 应该有一个内置的json解析器,但我们仍旧需要自己实现.Douglas Crockford,JSON的创造者,已经实现了一个解析器供你使用。可以从这里下载。

简单地导入该脚本,你就能获得一个新的json全局对象,用于解析你的.json文件.

var response = JSON.parse(xhr.responseText); 
var container = document.getElementById(&#39;container&#39;); 
for(var i = 0, len = response.length; i < len; i++) {     
container.innerHTML += &#39;<li>&#39; + response[i].name + &#39; : &#39; + response[i].email + &#39;</li>&#39;;
 }
Copy after login

24.删除''language''

在script标签内最常见的language属性,现在已经不用了  

The above is the detailed content of Practical use of javascript for beginners. 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