24 Practical Tips for JavaScript Beginners [TUTS]_javascript skills
注:本文多次用到Firebug的console对象,请参考Firebug Console API 。关于firebug的更详细介绍,请猛击这里。
1. 用 === 代替 ==
JavaScript里有两种不同的相等运算符:===|!== 和==|!=。相比之下,前者更值得推荐。请尽量使用前者。
引用:
“如果两个比较对象有着同样的类型和值,===返回true,!==返回false。”
– JavaScript: The Good Parts
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 文档
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>
当需要执行冗长的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>
这样好多了
代码:
<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
引用:
“把你踩在全局的那些乱七八糟的脚印都归于一人名下,能显著降低与其他应用、小工具或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>
9. 写好注释
可能一开始你会觉得并无必要,但相信我,你将来会主动想要尽可能写好代码的注释的。当你几个月后再回看某项目时,结果却发现很难想起当时写某句东西时脑子在想的什么了,是不是很让人沮丧呢?或者,如果有同事要修订你的代码呢?一定,一定要为你代码里的重要部分加上注释。
代码:
<font face="新宋体">// 遍历数组,输出各自名称<br>for(var i = 0, len = array.length; i < len; i++) {<BR> console.log(array);<BR>}</FONT>
一定要记得为未启用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>
代码:
<FONT face=新宋体>setInterval(someFunction, 3000);</FONT>
初识之下,“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>
代码:
<FONT face=新宋体>var o = being.person.man.bodyparts;<BR>o.arms = true;<BR>o.legs = true;</FONT>
在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
新建数组时的同类型运用。
行得通的写法
代码:
<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
代码:
<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>
遍历对象时,你可能会发现你还需要获取方法函数。所以遇到这种情况时,请一定记得给你的代码包一层 if 语句,用以过滤信息。
代码:
<FONT face=新宋体>for(key in object) {<BR> if(object.hasOwnProperty(key) {<BR> ...then do something...<BR> }<BR>}</FONT>
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>
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:
-
Object-Oriented JavaScript(No Chinese version yet)
-
JavaScript: The Good Parts(Chinese version)
-
Learning jQuery 1.3(There is no Chinese version yet, but you can check out the Chinese version of the old version)
-
Learning JavaScript(Chinese version)
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).
Code:
<font face="新宋体">(function doSomething() {<code id="code28"><font face="新宋体">(function doSomething() {<br> return {<br> name: 'jeff',<br> lastName: 'way'<br> };<br>})();</font>
return {
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
<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>
<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 = '
for more introduction
<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.

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

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 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 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

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 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 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.

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.

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
