32个JavaScript编程技巧

1个 (1)

避免在全局范围内定义变量; 试图在局部函数范围内定义它们。 因为:

  • Look-up is performed every time a variable is accessed.

•每次访问变量时都会执行查找。

  • Variables are resolved backwards from most specific to least specific scope.

•变量从最具体的范围到最不具体的范围向后解析。

  • Any variable created without the var keyword is created at the global scope and is not

不使用不是

     garbage collected when the function returns (because it doesn’t go out of scope), presenting the

函数返回时收集的垃圾(因为它不会超出范围),显示

     opportunity for a memory leak. Therefore, use variables in the same scope whenever possible,

内存泄漏的机会。 因此,请尽可能在相同范围内使用变量,

     and avoid global variables at all costs.

并不惜一切代价避免使用全局变量。

2 (2)

使用全局数组,全局对象或名称空间前缀。 如果需要全局变量,请使用包含所有全局变量的全局对象,如下所示:
var myBulletinBoardAppGlobals = {
    foo: "some value",
    bar: null
};
CPWFoo = "some value";
CPWBar = null;

3 (3)

使用{}代替new Object()。

For instance:

例如:

var o = {         // better than var o= new Object; o.name= ... (etc.)
   name: 'Jeffrey',
   lastName = 'Way',
   someFunction : function() {
      console.log(this.name);
   }
};
var o = {};

4 (4)

使用[]代替new Array()。
var a = ['Joe','Plumber'];  // better than var a= new Array()

5 (5)

使用一元+运算符键入转换为数字

In JavaScript, the + operator is used for both addition and concatenation. This can cause problems when adding up form field values, for example, since JavaScript is a non-typed language.  Form field values will be treated as strings, and if you add them with +, JavaScript will treat it as concatenation instead of addition.

在JavaScript中,+运算符用于加法和串联。 例如,由于JavaScript是非类型化的语言,因此在添加表单字段值时可能会导致问题。 表单字段值将被视为字符串,并且如果使用+进行添加,JavaScript会将其视为连接而不是添加。

To fix this problem, JavaScript needs a hint to tell it to treat the values as numbers, rather than strings. You can use the unary + operator to convert the string value into a number.  Prefixing a variable or expression with + will force it to evaluate as a number, which can then be successfully used in a math operation.

要解决此问题,JavaScript需要提示以告知其将值视为数字而不是字符串。 您可以使用一元+运算符将字符串值转换为数字。 给变量或表达式加上+前缀将迫使其以数字形式求值 ,然后可以在数学运算中成功使用它。

Good Practice

良好作法

function total() {
    var theform = document.forms["myform"];
    var total = (+theform.elements["val1"].value) + (+theform.elements["val2"].value);
    alert(total); // This will alert 3
}

Not As Good

不太好

<form name="myform" action="[url]">
<input type="text" name="val1" value="1">
<input type="text" name="val2" value="2">
</form>
function total() {
    var theform = document.forms["myform"];
    var total = theform.elements["val1"].value + theform.elements["val2"].value;
    alert(total); // This will alert "12", but what you wanted was 3!
}

6 (6)

为防止代码无法到达,在return,break,continue或throw语句后应加上}或case或默认值。

7 (7)

Avoid the eval method, it effectively requires the browser to create an entirely new scripting environment, import all variables from the current scope, execute the script, collect the garbage, and export the variables back into the original environment. Additionally, the code cannot be cached for optimization purposes, and might be vulnerable to script injection attacks.

避免使用eval方法,它实际上需要浏览器创建一个全新的脚本环境,从当前作用域导入所有变量,执行脚本,收集垃圾,并将变量导出回原始环境。 此外,无法出于优化目的而缓存代码,并且可能容易受到脚本注入攻击。

8 (8)

使用typeof检查时,请勿在typeof中使用括号。

9 (9)

最好总是使用= = =和!= =运算符。 = =和!=运算符确实会强制输入。 特别是,请勿使用= =与伪造的值进行比较。

For Example:

例如:

'' = = '0'          // false
0 = = ''            // true
0 = = '0'           // true
false = = 'false'   // false
false = = '0'       // true
false = = undefined // false
false = = null      // false
null = = undefined  // true

' \t\r\n ' = = 0    // true

10.始终将[i] radix [/ i]参数与parseInt一起使用 (10. Always use a [i]radix[/i] parameter with parseInt)

parseInt is a function that converts a string into an integer. It stops when it sees a nondigit, so parseInt("16") and parseInt("16 tons") produce the same result. It would be nice if the function somehow informed us about the extra text, but it doesn't.

parseInt是将字符串转换为整数的函数。 当它看到一个数字时它停止,因此parseInt(“ 16”)和parseInt(“ 16吨”)产生相同的结果。 如果函数以某种方式告知我们有关多余文本的信息,那会很好,但事实并非如此。

If the first character of the string is 0, then the string is evaluated in base 8 instead of base 10. In base 8, 8 and 9 are not digits, so parseInt("08") and parseInt("09") produce 0 as their result. This error causes problems in programs that parse dates and times. Fortunately, parseInt can take a radix parameter, so that parseInt("08", 10) produces 8.

如果字符串的第一个字符为0 ,则该字符串将以8为底,而不是以10为底。以8、8和9为底数不是数字,因此parseInt(“ 08”)和parseInt(“ 09”)产生0作为他们的结果。 此错误导致解析日期和时间的程序中的问题。 幸运的是,parseInt可以采用基数参数,以便parseInt(“ 08”,10)产生8。

11.返回声明 (11. return Statement)

具有值的return语句不应在值周围使用()(括号)。 返回值表达式必须与return关键字在同一行开始,以避免插入分号。

12.继续声明 (12. continue Statement)

Avoid use of the continue statement.  It tends to obscure the control flow of the function.

避免使用continue语句。 它倾向于使功能的控制流程模糊。

13.附声明 (13. with Statement)

不能使用with语句

14.加载后组件 (14. Post-load Components)

您可以仔细查看您的页面,然后问自己:“最初呈现页面绝对需要什么?”。 其余的内容和组件可以等待。

JavaScript is an ideal candidate for splitting before and after the onload event. For example if you have JavaScript code and libraries that do drag and drop and animations, those can wait, because dragging elements on the page comes after the initial rendering. Other places to look for candidates for post-loading include hidden content (content that appears after a user action) and images below the fold.

JavaScript是onload事件之前和之后进行拆分的理想选择。 例如,如果您有执行拖放操作和动画JavaScript代码和库,则这些操作可以等待,因为页面上的拖动元素是在初始渲染之后进行的。 寻找后加载候选的其他地方包括隐藏内容(用户操作后出现的内容)和首屏以下的图像。

See: http://ajaxpatterns.org/On-Demand_Javascript

请参阅: http : //ajaxpatterns.org/On-Demand_Javascript

15.预紧组件 (15. Preload Components)

预加载可能看起来与后加载相反,但实际上有一个不同的目标。 通过预加载组件,您可以利用浏览器空闲的时间来请求将来需要的组件(例如图像,样式和脚本)。 这样,当用户访问下一页时,您可能已经在缓存中包含了大多数组件,因此页面的加载将为用户带来更快的速度。

16.不要将字符串传递给“ SetInterval”或“ SetTimeOut” (16. Don't Pass a String to 'SetInterval' or 'SetTimeOut')

考虑以下代码:
setInterval(
"document.getElementById('container').innerHTML += 'My new number: ' + i", 3000
);
setInterval(someFunction, 3000);
setTimeout(function () {
    // Code to execute on a timeout
}, 50);

17.将昂贵的查找结果缓存在局部变量中 (17. Cache the result of expensive look-ups in local variables)

Good Practice

良好作法

var arr = ...;
var globalVar = 0;
(function () {
    var i, l, localVar;
    l = arr.length;
    localVar = globalVar;
    for (i = 0; i < l; i++) {
        localVar++;
    }
    globalVar = localVar;
})();

Not As Good

不太好

var arr = ...;
var globalVar = 0;
(function () {
    var i;
    for (i = 0; i < arr.length; i++) {
        globalVar++;
    }
})();

18.不要使用RegExp构造函数 (18. Don’t use the RegExp constructor)

除非使用正则表达式在运行时进行汇编,否则不要使用RegExp构造函数。 而是使用正则表达式文字。

19 (19)

In regular expressions use the test method if all you want to do is test for a pattern (the exec method carries a small performance penalty).

在正则表达式中,如果您只想测试一个模式,则使用test方法( exec方法带来的性能损失很小)。

if (/loaded|complete/.test(document.readyState)) {...}

20.基本操作通常比相应的函数调用更快 (20. Primitive operations are often faster than the corresponding function calls)

Good Practice

良好作法

var a = 1, b = 2, c;
c = a < b ? a : b;	var a = 1, b = 2, c;
c = Math.min(a, b);

Not As Good

不太好

var a = 1, b = 2, c;
c = Math.min(a, b);

Good Practice

良好作法

myArray[myArray.length] = value;
myArray[idx++] = value;
myArray.push(value);

Not As Good

不太好

myArray.push(value);

21 (21)

避免在性能关键的部分中使用try ... catch:

Good Practice

良好作法

var i;
try {
    for (i = 0; i < 100000; i++) {
        ...
    }
} catch (e) {
    ...
}

Not As Good

不太好

var i;
for (i = 0; i < 100000; i++) {
    try {
        ...
    } catch (e) {
        ...
    }
}

22.在性能关键的部分中避免…… (22. Avoid for…in in performance-critical sections)

Good Practice

良好作法

var i, value, length = myArray.length;
for (i = 0; i < length; i++) {
    value = myArray[i];
    ...
}

Not As Good

不太好

var key, value;
for (key in myArray) {
    value = myArray[key];
    ...
}

23 (23)

每当分支条件不变时,在外部而不是内部分支。

Good Practice

良好作法

var fn;
if (...) {
    fn = function () {...};
} else {
    fn = function () {...};
}

Not As Good

不太好

function fn () {
    if (...) {
        ...
    } else {
        ...
    }
}

24.最小化DOM访问 (24. Minimize DOM Access)

使用JavaScript访问DOM元素的速度很慢,因此,为了使页面更具响应性,您应该:

  •  Cache references to accessed elements

•缓存对已访问元素的引用

  •  Update nodes "offline" and then add them to the tree i.e. use display:none while adding then

•更新节点“离线”,然后将其添加到树中,即在添加时使用display:none

     change it to display:block.

更改为display:block。

  •  Avoid fixing layout with JavaScript i.e. don’t change the styles through javaScript use the

•避免使用JavaScript修复布局,即不要通过javaScript更改样式,请使用

     appropriate style classes.

适当的样式类。

25.减少DOM元素的数量 (25. Reduce the Number of DOM Elements)

复杂的网页意味着要下载更多字节,也意味着JavaScript中的DOM访问速度较慢。 例如,当您想添加事件处理程序时,如果在页面上循环访问500或5000个DOM元素,则会有所不同。

The number of DOM elements is easy to test, just type in Firebug's console:

只需输入Firebug的控制台即可轻松测试DOM元素的数量:

document.getElementsByTagName('*').length

26. DocumentFragment的使用 (26. Use of DocumentFragment)

DocumentFragment(DOM级别1核心)是轻量级的Document对象。

It supports only a subset of the regular DOM methods and properties.

它仅支持常规DOM方法和属性的子集。

var i, j, el, table, tbody, row, cell, docFragment;
docFragment = document.createDocumentFragment();
el = document.createElement("div");
docFragment.appendChild(el);
table = document.createElement("table");
el.appendChild(table);
tbody = document.createElement("tbody");
table.appendChild(tbody);
for (i = 0; i < 1000; i++) {
    ...
}
document.body.appendChild(docFragment);

27.使用innerHTML (27. Use of innerHTML)

如果需要在文档树中进行重大修改,请使用innerHTML

Good Practice

良好作法

var i, j, el, idx, html;
idx = 0;
html = [];
html[idx++] = "<table>";
for (i = 0; i < 1000; i++) {
    html[idx++] = "<tr>";
    for (j = 0; j < 5; j++) {
        html[idx++] = "<td></td>";
    }
    html[idx++] = "</tr>";
}
html[idx++] = "</table>";
el = document.createElement("div");
document.body.appendChild(el);
el.innerHTML = html.join("");

Not As Good

不太好

var i, j, el, table, tbody, row, cell;
el = document.createElement("div");
document.body.appendChild(el);
table = document.createElement("table");
el.appendChild(table);
tbody = document.createElement("tbody");
table.appendChild(tbody);
for (i = 0; i < 1000; i++) {
    row = document.createElement("tr");
    for (j = 0; j < 5; j++) {
        cell = document.createElement("td");
        row.appendChild(cell);
    }
    tbody.appendChild(row);
}

28. cloneNode的使用 (28. Use of cloneNode)

以防万一需要在文档树中再次创建相同的元素,然后再次使用cloneNode而不是createElement:

Good Practice

良好作法

var i, el, table, tbody, template, row, cell;
el = document.createElement("div");
document.body.appendChild(el);
table = document.createElement("table");
el.appendChild(table);
tbody = document.createElement("tbody");
table.appendChild(tbody);
template = document.createElement("tr");
for (i = 0; i < 5; i++) {
    cell = document.createElement("td");
    template.appendChild(cell);
}
for (i = 0; i < 1000; i++) {
    row = template.cloneNode(true);
    tbody.appendChild(row);
}

Not As Good

不太好

var i, j, el, table, tbody, row, cell;
el = document.createElement("div");
document.body.appendChild(el);
table = document.createElement("table");
el.appendChild(table);
tbody = document.createElement("tbody");
table.appendChild(tbody);
for (i = 0; i < 1000; i++) {
    row = document.createElement("tr");
    for (j = 0; j < 5; j++) {
        cell = document.createElement("td");
        row.appendChild(cell);
    }
    tbody.appendChild(row);
}

29.使用事件委托 (29. Use event delegation)

事件委托对Web应用程序的性能有以下好处:

   o Fewer functions to manage

o更少的功能需要管理

   o Takes up less memory.

o占用较少的内存。

   o Fewer ties between your code and the DOM

o您的代码和DOM之间的联系更少

   o Don't need to worry about removing event handlers when changing the DOM via innerHTML.

o通过innerHTML更改DOM时,无需担心删除事件处理程序。

30.经常访问时使用对象而不是文字 (30. Use objects instead of literals when accessed often)

Any properties and methods are defined on the string object, not the value. When you reference a property or method of a string value, the ECMAScript engine must implicitly create a new string object with the same value as your string, before running the method. This object is only used for that one request, and will be recreated next time you attempt to use a method of the string value.

任何属性和方法都在字符串对象上定义,而不是在值上定义。 当您引用字符串值的属性或方法时,ECMAScript引擎必须在运行该方法之前隐式创建一个与您的字符串具有相同值的新字符串对象。 该对象仅用于该请求,下次您尝试使用字符串值的方法时,将重新创建该对象。

If your code calls methods of literal values very often, you should consider converting them into objects instead, as in the previous example.

如果您的代码经常调用文字值的方法,则应考虑将其转换为对象,如上例所示。

31.避免递归 (31. Avoid Recursion)

JavaScript不提供尾递归优化。 因此,重复出现太深的功能最终将失败。

32.优化循环 (32. Optimize loops)

如果执行不正确,循环会变得非常慢。 最常见的错误之一是每次迭代都读取数组的length属性。 这意味着每次循环运行时,JavaScript需要读取数组的长度。 我们可以通过将长度值存储在另一个变量中来避免这种情况:

Good Practice

良好作法

var names = ['George','Ringo','Paul','John'];
var all = names.length;
for(var i=0;i<all;i++){
  doSomeThingWith(names[i]);
}
...OR...
var names = ['George','Ringo','Paul','John'];
for(var i=0,j=names.length;i<j;i++){
  doSomeThingWith(names[i]);
}

Not As Good

不太好

var names = ['George','Ringo','Paul','John'];
for(var i=0;i<names.length;i++){
  doSomeThingWith(names[i]);
}

[Editor's Note] These tips appear to have been compiled from numerous web sites.  Here is a partial listing:

[编者注]这些技巧似乎是从许多网站编译而来的。 以下是部分清单:

http://developer.yahoo.com/performance/rules.html http://developer.yahoo.com/performance/rules.html http://www.slideshare.net/julien.lecomte/high-performance-ajax-applications http://www.slideshare.net/julien.lecomte/high-performance-ajax-applications http://javascript.crockford.com/code.html http://javascript.crockford.com/code.html http://drupal.org/node/172169 http://drupal.org/node/172169

翻译自: https://www.experts-exchange.com/articles/3534/32-JavaScript-Programming-Tips.html

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值