JS 代码模式1

// Warning: doesn't pass JSLint
var i,
    hasOwn = Object.prototype.hasOwnProperty;
for (i in man) if (hasOwn.call(man, i)) { // filter
    console.log(i, ":", man[i]);
}

function func() { var a = 1, b = 2, sum = a + b, myobject = {}, i, j; // function body... }


好处:1.在函数的统一的区域可以查找到所有的局部变量
      2.防止在定义前使用变更错误
      3.使全局变量出现的可能性缩小,增强代码可读性
      4.更少的代码

   for循环

对于下面循环方式是非常低效的,特别对于HTMLCollections对象,因为每一次遍历都要重新计算length,推荐把length用变量缓存起来
// sub-optimal loop1
for (var i = 0; i < myarray.length; i++) {
    // do something with myarray[i]
}
HTMLCollections are objects returned by DOM methods such as:
• document.getElementsByName()
• document.getElementsByClassName()
• document.getElementsByTagName()
document.images
document.links
document.forms
document.forms[0].elements

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


当遍历一个对象的属性时,可以使用hasOwnProperty方法进行过滤。例如:


// the object
var man = {
    hands: 2,
    legs: 2,
    heads: 1
};
// 为object增加clone方法
if (typeof  Object.prototype.clone === "undefined") {
    Object.prototype.clone = function () {};
}

for (var i in man) {
    if (man.hasOwnProperty(i)) { // filter
        console.log(i, ":", man[i]);
    }
}
/*
result in the console
hands : 2
legs : 2
heads : 1
*/

// 反模式
// for-in loop without checking hasOwnProperty()
for (var i in man) {
    console.log(i, ":", man[i]);
}

/*
result in the console
hands : 2
legs : 2
heads : 1
clone: function()
*/

如果man对象有hasOwnProperty同名方法会出现问题,利用如下方法解决


for (var i in man) {
    if (Object.prototype.hasOwnProperty.call(man, i)) { // filter
        console.log(i, ":", man[i]);
    }
}

也可以将Object.prototype.hasOwnProperty;进行缓存:

var i,
    hasOwn = Object.prototype.hasOwnProperty;
for (i in man) {
    if (hasOwn.call(man, i)) { // filter
        console.log(i, ":", man[i]);
    }
}

也可以把for与if写在一起



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值