Home >Web Front-end >JS Tutorial >Follow me to learn the for loop and for...in loop of javascript_javascript skills

Follow me to learn the for loop and for...in loop of javascript_javascript skills

WBOY
WBOYOriginal
2016-05-16 15:31:381097browse

Everyone knows that JavaScript provides two ways to iterate objects:

  • for loop;
  • for..in loop;

1. for loop

Inadequacy:

The length of the array must be obtained every time it is looped;
Termination conditions should be clear;
In a for loop, you can loop through the values ​​of an array or array-like objects, such as arguments and HTMLCollection objects. The usual loop form is as follows:

// 次佳的循环
for (var i = 0; i < myarray.length; i++) {
 // 使用myarray[i]做点什么
}

The disadvantage of this form of loop is that the length of the array must be obtained each time it is looped. This will reduce the performance of your code, especially when myarray is not an array, but an HTMLCollection object.

HTMLCollections refers to the objects returned by DOM methods, for example:

document.getElementsByName()
document.getElementsByClassName()
document.getElementsByTagName()

There are other HTMLCollections that were introduced before the DOM standard and are still in use today. Yes:

document.images: All image elements on the page
document.links: All a tag elements
document.forms : all forms
document.forms[0].elements : All fields in the first form on the page

The trouble with collections is that they query the underlying document (HTML page) in real time. This means that every time you access the length of any collection, you have to query the DOM in real time, and DOM operations are generally expensive.

This is why it is good form to cache the length of an array (or collection) when you loop over values, as shown in the following code:

for (var i = 0, max = myarray.length; i < max; i++) {
 // 使用myarray[i]做点什么
}

In this way, you only retrieve the length value once during this loop.

Cache the length of HTMLCollections when looping to retrieve content is faster in all browsers, between 2x (Safari3) and 190x (IE7). //This data looks very old

Note that when you explicitly want to modify the collection in the loop (e.g., add more DOM elements), you may prefer length updates rather than constants.

With the single var form, you can pull the variable out of the loop, like this:

function looper() {
 var i = 0,
  max,
  myarray = [];
 // ...
 for (i = 0, max = myarray.length; i < max; i++) {
  // 使用myarray[i]做点什么
 }
}

This form has the benefit of consistency because you stick to a single var form. The downside is that when refactoring code, copying and pasting the entire loop is a bit difficult. For example, if you copy a loop from one function to another, you have to make sure that you can introduce i and max into the new function (if they are not useful here, you will most likely have to delete them from the original function) Lose).

The last adjustment to the loop is to replace i with one of the expressions below.

i = i + 1
i += 1

JSLint prompts you to do this because and -- promote "excessive trickiness". If you ignore it, JSLint's plusplus option will be false (the default is default).

Two variations:

  • One variable is missing (no max)
  • Counting down to 0 is usually faster because comparing to 0 is more efficient than comparing to the array length or anything else that is not 01
//第一种变化的形式:

var i, myarray = [];
for (i = myarray.length; i–-;) {
 // 使用myarray[i]做点什么
}

//第二种使用while循环:

var myarray = [],
 i = myarray.length;
while (i–-) {
 // 使用myarray[i]做点什么
}

These small improvements are only for performance, in addition JSLint will complain about using i--.

2. for…in loop—also known as “enumeration”

The for…in loop is often used to iterate the properties of an object or each element of an array. The loop counter in the for…in loop is a string, not a number. It contains the name of the current property or the index of the current array element. Here are a few examples:

When traversing an object, the variable i, which is the loop counter, is the attribute name of the object:

//使用for..in循环遍历对象属性 
varperson={ 
 name: "Admin", 
 age: 21, 
 address:"shandong" 
}; 
for(var i in person){ 
 console.log(i); 
} 

The execution result is:

name

age

address

When traversing an array, the variable i, which is the loop counter, is the index of the current array element:

//使用for..in循环遍历数组 
vararray = ["admin","manager","db"] 
for(vari in array){ 
 console.log(i); 
} 

Execution result:

0

1

2

However, now it seems that the for.. in loop is quite easy to use. However, don’t be too happy too early. Take a look at the following example:

var array =["admin","manager","db"]; 
//给Array的原型添加一个name属性 
Array.prototype.name= "zhangsan"; 
for(var i in array){ 
 alert(array[i]); 
} 

运行结果:

admin

manager

db

zhangsan
咦,奇观了,怎么平白无故的冒出来一个zhangsan
现在,再看看使用 for循环会怎样?

vararray = ["admin","manager","db"]; 
//给Array的原型添加一个name属性 
Array.prototype.name = "zhangsan"; 
for(var i =0 ; i<array.length; i++){ 
 alert(array[i]); 
}; 

运行结果:

admin

manager

db
哦, 现在明白了,for..in循环会把某个类型的原型(prototype)中方法与属性给遍历出来,所以这可能会导致代码中出现意外的错误。为了避免这个问题,我们可以使用对象的hasOwnProperty()方法来避免这个问题,如果对象的属性或方法是非继承的,那么hasOwnProperty() 方法返回true。即这里的检查不涉及从其他对象继承的属性和方法,只会检查在特定对象自身中直接创建的属性。

vararray = ["admin","manager","db"]; 
Array.prototype.name= "zhangshan"; 
for(var i in array){ 
//如果不是该对象自身直接创建的属性(也就是该属//性是原型中的属性),则跳过显示 
 if(array.hasOwnProperty(i)){ 
  alert(array[i]); 
  }
} 

运行结果:

admin

manager

db
另外一种使用hasOwnProperty()的形式是取消Object.prototype上的方法。像这样:

// 对象
var man = {
 hands: 2,
 legs: 2,
 heads: 1
};
for (var i in man) {
 if (Object.prototype.hasOwnProperty.call(man, i)) { // 过滤
  console.log(i, ":", man[i]);
 }
}

其好处在于在man对象重新定义hasOwnProperty情况下避免命名冲突。也避免了长属性查找对象的所有方法,你可以使用局部变量“缓存”它。

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

严格来说,不使用hasOwnProperty()并不是一个错误。根据任务以及你对代码的自信程度,你可以跳过它以提高些许的循环速度。但是当你对当前对象内容(和其原型链)不确定的时候,添加hasOwnProperty()更加保险些。

格式化的变化(通不过JSLint)会直接忽略掉花括号,把if语句放到同一行上。其优点在于循环语句读起来就像一个完整的想法(每个元素都有一个自己的属性”X”,使用”X”干点什么):

// 警告: 通不过JSLint检测
var i, hasOwn = Object.prototype.hasOwnProperty;
for (i in man) if (hasOwn.call(man, i)) { // 过滤
 console.log(i, ":", man[i]);
}

以上就是介绍了JavaScript提供的两种方式迭代对象:for循环和for...in循环,希望这篇文章对大家的学习有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn