// 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写在一起