首页 > 网站 > WEB开发 > 正文

JavaScript Patterns 2.3 For loops

2024-04-27 14:24:00
字体:
来源:转载
供稿:网友

javaScript Patterns 2.3 For loops

2014-05-17 10:14 by 小郝(Kaibo Hao), ... 阅读, ... 评论, 收藏, 编辑

HTMLCollections are objects returned by DOM methods such as:

• document.getElementsByName()

• document.getElementsByClassName()

• document.getElementsByTagName()

HTMLCollections, which were introduced before the DOM standard and are still in use today

document.images

All IMG elements on the page

document.links

All A elements

document.forms

All forms

document.forms[0].elements

All fields in the first form on the page

// used i+=1 instead of i++ to follow the rule of JSLint

for (var i = 0, max = myarray.length; i < max; i += 1) {    // do something with myarray[i]} 

• Use one less variable (no max)

• Count down to 0, which is usually faster because it's more efficient to compare to 0 than to the length of the array or to anything other than 0

The first modified pattern is:

var i, myarray = [];for (i = myarray.length; i--;) {    // do something with myarray[i]} 

And the second uses a whileloop:

var myarray = [],i = myarray.length;while (i--) {    // do something with myarray[i]} 

上一篇:Keypress

下一篇:系统设计的一些心得

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表