Practical use of javascript for beginners
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
However, consider this code again:
if(someVariableExists) x=false anotherFunctionCall();
Some people may think that the previous code is equivalent Yu:
if(someVariableExists){ x = false; anotherFunctionCall();
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";
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>
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('container'); container.innerHtml += 'my number: ' + i; console.log(i); }
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('container'); for(var i = 0, len = someArray.length; i < len; i++) { container.innerHtml += 'my number: ' + i; console.log(i); }
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 = ['item 1', 'item 2', 'item 3', ...]; var list = '<ul><li>' + arr.join('</li><li>') + '</li></ul>';
"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 = 'jeffrey'; var lastname = 'way'; function doSomething(){...} console.log()
Better approach
var DudeNameSpace = { name:'Jeffrey'; lastname:'way', doSometing: function(){...} } console.log(DudeNameSpace.name);
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('container').innerHTML += 'my new number: ' + i", 3000 );
这段代码不仅抵消,而且其行为与"eval"函数相同.永远不要传给字符串给SetInterval和SetTimeout.相反,颍川地一个函数名.
setInterval(someFunction, 3000);
12.不要使用"with"语句
乍一看,'with'语句似乎是个聪明的想法.基本概念是他们能够为深度嵌套对象提供一种简写方式,例如...
with (being.person.man.bodyparts) { arms = true; legs = true; }
取代如下写法
being.person.man.bodyparts.arms = true; being.person.man.bodyparts.legs = true;
很不幸,经过一些测试,会发现这种简写在设置新成员时表现非常糟糕.作为替代.你应该使用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: 'Jeffrey', lastName: 'Way', someFunction: function() { console.log(this.name); } };
注意如果你只是想简单地创建个空对象,{}就派上用场了.
var o = {};
对象字面量使我们能够编写支持很多特性的代码,并对代码的实现者来说代码仍然相对直观,不需要直接调用构造器或维护传递给函数的参数的正确顺序,等等.
14.使用[]而不是New Array()
这同样适用于创建一个新数组
过去的写法
var a = new Array(); a[0] = 'Joe'; a[1] = 'Plumber';
更好的写法 var a = ['Joe', 'Plumber'];
Javascript中一个常见的错误是需要数组时使用对象或需要对象时使用数组,规则很简单:当属姓名是小的连续整数时,你应该使用数组,否则,使用对象
15.一长串变量? 省略''var''关键字,使用逗号替代
var someItem = 'some string'; var anotherItem = 'another string'; var oneMoreItem = 'one more string';
更好的写法
var someItem = 'some string', anotherItem = 'another string', oneMoreItem = 'one more string';
相当的不言自明,我不知道这里是否有任何真正的速度提升,但是它使你的代码更加简洁了.
16.始终,始终使用分号
技术上来说,大多数浏览器都允许你省略一些分号
var someItem = 'some string' function doSomething() { return 'something' }
话虽如此,但这是一种非常糟糕的做法,可能导致更大的问题,问题查找起来也更困难
更好的写法
var someItem = 'some string'; function doSomething() { return 'something'; }
18.For in 语句
遍历对象内的成员时,你也会得到方法函数,为了解决这个问题,应始终将你的代码包装在一个if语句中来过滤信息
for(key in object) { if(object.hasOwnProperty(key)) { ... then do something... } }
19.使用firebug的''Timer''特性来优化代码
需要一种快速简单地方法来检测一个操作花费多长时间么?
使用Firebug的timer特性记录结果
function TimeTracker() { console.time("MyTimer"); for(x=5000; x > 0; x--){} console.timeEnd("MyTimer"); }
20.读书 面向对象的JavaScript
JavaScript:语言精粹
学习jQuery 1.3
学习JavaScript
21.自执行函数(self-executing functions)
相比调用函数,当页面加载或调用父函数时,让函数自动执行会简单些.简单地将你的函数包装在圆括号内,并添加额外的一对圆括号,其本质上就调用了这个函数
(function doSomething() { return { name: 'jeff', lastName: 'way' }; })();
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('container'); for(var i = 0, len = response.length; i < len; i++) { container.innerHTML += '<li>' + response[i].name + ' : ' + response[i].email + '</li>'; }
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!

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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

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

CrystalDiskMark is a small HDD benchmark tool for hard drives that quickly measures sequential and random read/write speeds. Next, let the editor introduce CrystalDiskMark to you and how to use crystaldiskmark~ 1. Introduction to CrystalDiskMark CrystalDiskMark is a widely used disk performance testing tool used to evaluate the read and write speed and performance of mechanical hard drives and solid-state drives (SSD). Random I/O performance. It is a free Windows application and provides a user-friendly interface and various test modes to evaluate different aspects of hard drive performance and is widely used in hardware reviews

foobar2000 is a software that can listen to music resources at any time. It brings you all kinds of music with lossless sound quality. The enhanced version of the music player allows you to get a more comprehensive and comfortable music experience. Its design concept is to play the advanced audio on the computer The device is transplanted to mobile phones to provide a more convenient and efficient music playback experience. The interface design is simple, clear and easy to use. It adopts a minimalist design style without too many decorations and cumbersome operations to get started quickly. It also supports a variety of skins and Theme, personalize settings according to your own preferences, and create an exclusive music player that supports the playback of multiple audio formats. It also supports the audio gain function to adjust the volume according to your own hearing conditions to avoid hearing damage caused by excessive volume. Next, let me help you

MetaMask (also called Little Fox Wallet in Chinese) is a free and well-received encryption wallet software. Currently, BTCC supports binding to the MetaMask wallet. After binding, you can use the MetaMask wallet to quickly log in, store value, buy coins, etc., and you can also get 20 USDT trial bonus for the first time binding. In the BTCCMetaMask wallet tutorial, we will introduce in detail how to register and use MetaMask, and how to bind and use the Little Fox wallet in BTCC. What is MetaMask wallet? With over 30 million users, MetaMask Little Fox Wallet is one of the most popular cryptocurrency wallets today. It is free to use and can be installed on the network as an extension

NetEase Mailbox, as an email address widely used by Chinese netizens, has always won the trust of users with its stable and efficient services. NetEase Mailbox Master is an email software specially created for mobile phone users. It greatly simplifies the process of sending and receiving emails and makes our email processing more convenient. So how to use NetEase Mailbox Master, and what specific functions it has. Below, the editor of this site will give you a detailed introduction, hoping to help you! First, you can search and download the NetEase Mailbox Master app in the mobile app store. Search for "NetEase Mailbox Master" in App Store or Baidu Mobile Assistant, and then follow the prompts to install it. After the download and installation is completed, we open the NetEase email account and log in. The login interface is as shown below

Cloud storage has become an indispensable part of our daily life and work nowadays. As one of the leading cloud storage services in China, Baidu Netdisk has won the favor of a large number of users with its powerful storage functions, efficient transmission speed and convenient operation experience. And whether you want to back up important files, share information, watch videos online, or listen to music, Baidu Cloud Disk can meet your needs. However, many users may not understand the specific use method of Baidu Netdisk app, so this tutorial will introduce in detail how to use Baidu Netdisk app. Users who are still confused can follow this article to learn more. ! How to use Baidu Cloud Network Disk: 1. Installation First, when downloading and installing Baidu Cloud software, please select the custom installation option.

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

Apple rolled out the iOS 17.4 update on Tuesday, bringing a slew of new features and fixes to iPhones. The update includes new emojis, and EU users will also be able to download them from other app stores. In addition, the update also strengthens the control of iPhone security and introduces more "Stolen Device Protection" setting options to provide users with more choices and protection. "iOS17.3 introduces the "Stolen Device Protection" function for the first time, adding extra security to users' sensitive information. When the user is away from home and other familiar places, this function requires the user to enter biometric information for the first time, and after one hour You must enter information again to access and change certain data, such as changing your Apple ID password or turning off stolen device protection.

Chirp Down can also be called JJDown. This is a video download tool specially created for Bilibili. However, many friends do not understand this software. Today, let the editor explain to you what Chirp Down is? How to use chirp down. 1. The origin of Chirpdown Chirpdown originated in 2014. It is a very old video downloading software. The interface adopts Win10 tile style, which is simple, beautiful and easy to operate. Chirna is the poster girl of Chirpdown, and the artist is あさひクロイ. Jijidown has always been committed to providing users with the best download experience, constantly updating and optimizing the software, solving various problems and bugs, and adding new functions and features. The function of Chirp Down Chirp Down is
