Table of Contents
引用:
代码:
Code:
Home Web Front-end JS Tutorial 24 Practical Tips for JavaScript Beginners [TUTS]_javascript skills

24 Practical Tips for JavaScript Beginners [TUTS]_javascript skills

May 16, 2016 pm 06:51 PM
javascript Practical advice newbie

注:本文多次用到Firebug的console对象,请参考Firebug Console API 。关于firebug的更详细介绍,请猛击这里
1. 用 === 代替 ==

JavaScript里有两种不同的相等运算符:===|!== 和==|!=。相比之下,前者更值得推荐。请尽量使用前者。

引用:
“如果两个比较对象有着同样的类型和值,===返回true,!==返回false。”

– JavaScript: The Good Parts
不过,如果使用==和!=,在操作不同数据类型时, 你可能会遇到一些意想不到的问题。在进行相等判断前,JavaScript会试图将它们转换为字符串、数字或 Boolean量。

2. 避免使用Eval函数

Eval函数把一个字串作为参数,并把字串作为JavaScript语句执行,返回结果(参考)。

此函数不仅会降低你脚本的执行效率,而且还大大增加了安全风险,因为它赋予了作为文本的参数太大的权利。千万别用!

3. 不要使用快速写法

技术上说,你可以省略掉大部分花括弧和句尾分号,绝大多数浏览器都能正确执行以下语句:
复制内容到剪贴板
代码:
<font face="新宋体">if(someVariableExists)<br>   x = false</font>
不过,如果是这样的呢:
复制内容到剪贴板
代码:
<font face="新宋体">if(someVariableExists)<br>   x = false<br>   anotherFunctionCall();</font>
你可能会认为它和下面的语句相等:
复制内容到剪贴板
代码:
<font face="新宋体">if(someVariableExists) {<br>   x = false;<br>   anotherFunctionCall();<br>}</font>
不幸的是,事实并非如此。现实情况是它等价于:
复制内容到剪贴板
代码:
<font face="新宋体">if(someVariableExists) {<br>   x = false;<br>}<br>anotherFunctionCall();</font>
如您注意到的,再漂亮的缩进也不能代替这华丽的花括弧。在所有情况下都请写清楚花括号和句尾分号。在只有一行语句的时候能偶尔省略掉,虽然下这么做也是极度不被推荐的:
复制内容到剪贴板
代码:
<font face="新宋体">if(2 + 2 === 4) return 'nicely done';</font>
多考虑下将来吧,孩子

假设,在将来的开发过程中,你需要为这个 if 语句添加更多的命令呢?到时候你还不是得把括号给加上?

4. 好好利用JS Lint

JSLint 是由 Douglas Crockford 编写的一个调试器。你只需要贴上你的代码,它就能快速为您扫描出任何明显的错误和问题。
引用:
“JSLint扫描接收的代码。发现问题,描述问题,并给出其在源码中的大概位置。可发现的问题包括但不限于语法错误,虽然语法错误确实是最常见的。JSLint也会用
约定俗成的习惯检查代码的格式化风格,以及结构错误。通过JSLint的扫描并不能保证你的程序就完全正确。它只是为您提供了额外一双发现错误的眼睛。”


– JSLint 文档
完成代码之前,把它放到JSLint里检查一下,快速消灭你的无心之过。

5. 在页面底部加载脚本

正如下图所示:


请记住—— 我们要千方百计保证客户端的页面载入速度尽可能的快。而脚本没载入完成,浏览器就没法加载页面的剩余部分。

如果你的JS文件只是添加一些额外功能——例如,为点击某链接绑定事件——那大可以等页面加载基本完成后再做。把JS文件放到页面最后,body的结束标签之前,这样做最好了。

更好的写法是
复制内容到剪贴板
代码:
<font face="新宋体"><p>超哥是世界上最帅的人。benhuoer.com是世界上最好看的博客。</p><br><script type="text/javascript" src="path/to/file.js"></script><br><script type="text/javascript" src="path/to/anotherFile.js"></script><br></body><br></html> <!--0--><!--1--></font>
6. 在 For 语句外部声明变量

当需要执行冗长的for语句时,不要让JavaScript引擎每次都重复那些没有必要的操作。例如:

这样不好
复制内容到剪贴板
代码:
<font face="新宋体">for(var i = 0; i < someArray.length; i++) {<BR> var container = document.getElementById('container');<BR> container.innerHtml += 'my number: ' + i;<BR> console.log(i);<BR>}</FONT>
这段代码每次都重新定义数组长度,每次都在遍历DOM寻找container元素 —— 太傻了!

这样好多了
复制内容到剪贴板
代码:
<FONT face=新宋体>var container = document.getElementById('container');<BR>for(var i = 0, len = someArray.length; i < len; i++) {<BR> container.innerHtml += 'my number: ' + i;<BR> console.log(i);<BR>}</FONT>
我要给留言改进这段代码的人额外惊喜!欢迎大家留言讨论!

7. 快速构建字串

要对一个数组或对象做循环操作时,不要老惦记着一表人才的for语句,拿点创意出来嘛!明明就还有很多更快的办法:
复制内容到剪贴板
代码:
<FONT face=新宋体>var arr = ['item 1', 'item 2', 'item 3', ...];<BR>var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';</font>
引用:
“没那么多繁文缛节来烦你;你就信我一次好了(或者你也可以自己试一试)—— 这真的是迄今能找到的最快办法了!

用点土办法,也别管它背后究竟发生了什么抽象的东西,通常土办法都比那些优雅的办法要快捷得多!”

– James Padolsey, james.padolsey.com
8. 减少全局变量
引用:
“把你踩在全局的那些乱七八糟的脚印都归于一人名下,能显著降低与其他应用、小工具或JS库冲突的可能性。”

– Douglas Crockford
复制内容到剪贴板
代码:
<font face="新宋体">var name = 'Jeffrey';<br>var lastName = 'Way';<br>function doSomething() {...}<br>console.log(name); // Jeffrey -- or window.name</font>
更好的写法
复制内容到剪贴板
代码:
<font face="新宋体">var DudeNameSpace = {<br>   name : 'Jeffrey',<br>   lastName : 'Way',<br>   doSomething : function() {...}<br>}<br>console.log(DudeNameSpace.name); // Jeffrey</font>
注意看,我们是如何戏剧化地把“乱七八糟的脚印”都归到“DudeNameSpace”这对象之下的。

9. 写好注释

可能一开始你会觉得并无必要,但相信我,你将来会主动想要尽可能写好代码的注释的。当你几个月后再回看某项目时,结果却发现很难想起当时写某句东西时脑子在想的什么了,是不是很让人沮丧呢?或者,如果有同事要修订你的代码呢?一定,一定要为你代码里的重要部分加上注释。
复制内容到剪贴板
代码:
<font face="新宋体">// 遍历数组,输出各自名称<br>for(var i = 0, len = array.length; i < len; i++) {<BR> console.log(array);<BR>}</FONT>
10. 试试渐进增强

一定要记得为未启用JavaScript的情况提供替代方案。大家可能会认为,“大部分我的访客都启用了JavaScript的,我才不用担心”。这样的话,你可就大错特错了!

你有没有试过看看禁用JavaScript后你那漂亮的滑动器都成啥样了?(你可以下载 Web Developer ToolBar 轻松完成这项任务。)禁用之后你的网站可能就彻底失去了可用性!经验之谈:开发初期总是按照没有JavaScript来设计你的网站,之后再进行渐进地功能增强,小心翼翼地改变你地布局。

11. 不要传递字串给 “setInterval” 或 “setTimeout”

看看下面的代码:
复制内容到剪贴板
代码:
<FONT face=新宋体>setInterval(<BR>"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000<BR>);</FONT>
不仅执行不高效,而且和 eval 函数有着同样的高风险。千万不要把字串传递给 setInterval 和 setTimeout。恰当的做法是,传递一个函数名:
复制内容到剪贴板
代码:
<FONT face=新宋体>setInterval(someFunction, 3000);</FONT>
12. 不要使用with语句

初识之下,“with”语句似乎还挺好用的。它用于设置代码在特定对象中的作用域。其基本用法是提供深入到对象中处理元素的快速写法。例如:
复制内容到剪贴板
代码:
<FONT face=新宋体>with (being.person.man.bodyparts) {<BR> arms = true;<BR> legs = true;<BR>}</FONT>
– 等价于 —
复制内容到剪贴板
代码:
<FONT face=新宋体>being.person.man.bodyparts.arms = true;<BR>being.person.man.bodyparts.legs= true;</FONT>
不幸的是,测试表明,若你要为对象插入新成员,with的表现非常糟糕,它的执行速度非常缓慢。替代方案是声明一个变量:
复制内容到剪贴板
代码:
<FONT face=新宋体>var o = being.person.man.bodyparts;<BR>o.arms = true;<BR>o.legs = true;</FONT>
13. 使用 {},而不用New Object()

在JavaScript有多种方式能新建对象。最传统的方法是 new 语句,如下:
复制内容到剪贴板
代码:
<FONT face=新宋体>var o = new Object();<BR>o.name = 'Benhuoer';<BR>o.lastName = 'Yang';<BR>o.someFunction = function() {<BR> console.log(this.name);<BR>}</FONT>
不过,这一方法读起来却比较糟糕。我强烈建议你采用下面这种在文字样式上更为强健的写法:

更好的写法
复制内容到剪贴板
代码:
<FONT face=新宋体>var o = {<BR> name: 'Jeffrey',<BR> lastName = 'Way',<BR> someFunction : function() {<BR> console.log(this.name);<BR> }<BR>};</FONT>
注意,如果你想新建一个空对象,用 {} 就能行:
复制内容到剪贴板
代码:
<FONT face=新宋体>var o = {};</FONT>
引用:
“对象字面符(Objects literals)帮助我们写出支持很多特性,同时又关联性强、简明直接的代码。没必要直接调用新建语句,然后再费心维护声明变量和传递变量的语句之间的正确顺序,等等。” – dyn-web.com
14. 使用[],而不用New Array()

新建数组时的同类型运用。

行得通的写法
复制内容到剪贴板
代码:
<FONT face=新宋体>var a = new Array();<BR>a[0] = "Joe";<BR>a[1] = 'Plumber';</FONT>
更好的写法
复制内容到剪贴板
代码:
<FONT face=新宋体>var a = ['Joe','Plumber'];</FONT>
引用:
“在JavaScript编程中经常遇到的一个错误是,该用数组时却用了对象,该用对象时却用了数组。规则其实很简单:当属性名是小的连续整数时,你应该使用数组。其他情况,使用对象。” – Douglas Crockford
15. 一长列变量声明?别写那么多var,用逗号吧
复制内容到剪贴板
代码:
<FONT face=新宋体>var someItem = 'some string';<BR>var anotherItem = 'another string';<BR>var oneMoreItem = 'one more string';</FONT>
更好的写法
复制内容到剪贴板
代码:
<FONT face=新宋体>var someItem = 'some string',<BR> anotherItem = 'another string',<BR> oneMoreItem = 'one more string';</FONT>
…不言自明。我不知道这样做能否提升代码执行速度,但是确实让你的代码干净许多。

17. 千万千万记得写分号

大部分浏览器都允许你不写句尾分号:
复制内容到剪贴板
代码:
<FONT face=新宋体>var someItem = 'some string'<BR>function doSomething() {<BR> return 'something'<BR>}</FONT>
之前已经说过,这样做会造成潜在的更大、更难以发现的问题:

更好的写法
复制内容到剪贴板
代码:
<FONT face=新宋体>var someItem = 'some string';<BR>function doSomething() {<BR> return 'something';<BR>}</FONT>
18. “For in” 语句

遍历对象时,你可能会发现你还需要获取方法函数。所以遇到这种情况时,请一定记得给你的代码包一层 if 语句,用以过滤信息。
复制内容到剪贴板
代码:
<FONT face=新宋体>for(key in object) {<BR> if(object.hasOwnProperty(key) {<BR> ...then do something...<BR> }<BR>}</FONT>
引自[/i][i] Douglas Crockford 所作:[/i][i] JavaScript: The Good Parts

19. 使用Firebug的“Timer”功能优化你的代码

想要轻松地快速了解某项操作的用时吗?使用Firebug的timer功能来记录结果好了。
复制内容到剪贴板
代码:
<FONT face=新宋体>function TimeTracker(){<BR>console.time("MyTimer");<BR>for(x=5000; x > 0; x--){}<br>console.timeEnd("MyTimer");<br>}</font>
20. Read, Read, Read…Read, Read, Read…

While I’m a huge fan of web development blogs (like this one!) There seems to be no choice but to read books before eating and going to bed~ Put a good book on web development on your bedside table! The following book list is my favorite:



Read them …read it many times! I'm still reading it now.

21. Self-determining function

Compared with calling a function, let the function automatically load when the page is loaded or a parent function is called. It is a very simple and convenient way to execute. You just wrap your function in a parent and add an extra parenthesis, which essentially triggers the function you defined (Learn more).
Copy content to clipboard
Code:
<font face="新宋体">(function doSomething() {<code id="code28"><font face="新宋体">(function doSomething() {<br>   return {<br>      name: 'jeff',<br>      lastName: 'way'<br>   };<br>})();</font> return {
name: 'jeff', lastName: 'way' };})();


22. Native JavaScript will always be faster than using a code library


JavaScript libraries such as jQuery and Mootools can save you a lot of time in the process of writing code - especially when AJAX operations are required. But you have to remember that as long as your code is written properly, native JavaScript will always execute faster than using a code library. jQuery’s “each” method is very convenient for loop operations, but using the original for statement will always be much faster.

23. Crockford’s JSON.Parse
Although JavaScript 2 will have a built-in JSON processor, at the time of writing this article, we You still need to implement it yourself. Douglas Crockford, the creator of JSON, has created a handler for us to use out of the box. You can download it here
.
By importing this code, you can create a new JSON global object and then process your .json file. <font face="新宋体">var response = JSON.parse(xhr.responseText); <br>var container = document.getElementById('container');<br>for(var i = 0, len = response.length; i < len; i ) {<br>container.innerHTML = '<li>' response.name ' : ' response.email '</li>';<br>}</font>
Copy content to clipboard Code:<font face="新宋体">var response = JSON.parse(xhr.responseText); </font>var container = document.getElementById('container');
for(var i = 0, len = response.length; i < len; i ) {
container.innerHTML = '
  • ' response.name ' : ' response.email '
  • ';}For JSON, please see
    for more introduction
    .
    24. Remove “Language” <font face="新宋体"><script type="text/javascript" language="javascript"><br>...<br></script></font>


    Many years ago, language was still a required attribute for every script tag: Copy content to clipboard Code:
    <font face="新宋体"><script type="text/javascript" language="javascript"><br>...</ script></font>But now, this attribute has been useless for a long time... So, delete it! That’s it, friends~That’s it, these are my 24 tips for JavaScript beginners. Dear friends, what do you think? Do you have any quick tips? Thank you for your patience in reading.
    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)
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. Best Graphic Settings
    2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
    R.E.P.O. How to Fix Audio if You Can't Hear Anyone
    2 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)

    Tips for playing the Mist Lock Kingdom to give newbies a guide Tips for playing the Mist Lock Kingdom to give newbies a guide Jan 28, 2024 pm 03:33 PM

    Mistlock Kingdom is an open world game where players can play as Sons of Fire to survive and explore. The game combines the unique entertainment of action RPG challenges, bringing players endless surprises and joy. In the game, players can explore resources, environments, weapons and more. Some novice players may be curious about how to get started with the game. In this introduction and sharing, we will provide you with some relevant getting started guides. Tips for Beginners to the Fog Lock Kingdom: The danger levels of areas shrouded by miasma are different. During the exploration process, new areas of the map will be gradually unlocked, and the location of the areas shrouded by miasma can be seen. The map will be distinguished by two colors. The blue area can be entered in a short time. The time you can stay will also be different depending on the character's ability level.

    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.

    Anchor Point Advent Novice Ten Company Character Recommendations Anchor Point Advent Novice Ten Company Character Recommendations Feb 20, 2024 pm 02:30 PM

    Anchor Arrival is a 3D turn-based card game with a high-definition beautiful girl two-dimensional theme. It provides a rich and exciting combination of characters for players to explore and experience. It has many powerful combinations of high-quality lineups. New players are also curious novices. What powerful characters are recommended in the pool? Let’s take a look at the selection reference for novices to win ten consecutive golds! Anchor Point Advent is a powerful character recommendation for novice pools. The first ten-consecutive pick is Alice. She is mainly a single-target lightning-type burst character. The output is very explosive, and the experience will be very friendly to newcomers, so it is highly recommended to choose it. It is recommended to choose the combination of "Alice" + "Antelope" for 10 points. Alice is the most worthy character to output the goldpire attribute, and is not even a bit stronger than the other two characters in the novice card pool. Alice can pass special

    Learning to use batch indentation is a skill that PyCharm newbies must master Learning to use batch indentation is a skill that PyCharm newbies must master Dec 30, 2023 pm 12:58 PM

    Essential skills for newbies to PyCharm: Mastering the use of batch indentation requires specific code examples Overview: PyCharm is a powerful Python integrated development environment (IDE) that provides many practical tools and functions to help developers improve efficiency . In the daily coding process, we often need to indent the code to keep the code format neat and beautiful. The batch indentation function provided by PyCharm can help us quickly batch indent the code and improve coding efficiency. This article will explore Py

    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 implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

    How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

    Ancient Crown Beginner's Guide and Gameplay Introduction Ancient Crown Beginner's Guide and Gameplay Introduction Feb 20, 2024 am 11:20 AM

    Crown of the Ancients is a high-quality and strategic card mobile game based on Western magical adventure. In-game secret exploration, ruins adventure, national championship and other special gameplay are waiting for you to experience. So for novice players, if they want to get started with this game quickly, a novice guide is indispensable. Today, the editor will bring you the relevant guide, let’s take a look. An overview of the Ancient Crown beginner’s guide, gameplay and area opening styles: 1. Diamond accumulation flow: Everything is focused on accumulating diamonds, and then you start to work hard after leaving the village. Except for the main magic weapon, three flywheel activities, etc., which require diamonds, the others are ignored. The main focus is on one of them. Don't pay attention to the hero challenge. You can fight as many as you can, and don't force it. Advantages: You only need to mess around to accumulate diamonds. After leaving the village, you can quickly access the latest activities with diamonds, get new series of hardware heroes, and diamonds are broken.

    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

    See all articles