JavaScript for loop --------------- references

 

  In ECMAScript5 (referred to as the ES5), for three cycles, namely:

  • Simple for loop

  • for-in

  • forEach

Here we take a look at the most common way to write:

 

 

 

When the array length does not change during the cycle, we should use variable length arrays stored, it will get better efficiency, improved following is written:

 

 

 

for-in

Under normal circumstances, we can use for-in to loop over the contents of the array, the following code

In general, the results are as follows:

 

 But doing so often problems.

for-in truth

for-in loop through a property of an object, rather than the array index. Therefore, for-in will traverse the object is not limited to the array, you can also traverse the object. Examples are as follows:

 

 

 The results are as follows:

 

 

 

Note that, for-in the order of traversal attribute is not determined, i.e., the output result of the order of the attribute in the order of the objects is independent, also independent of the alphabetical order attribute, it is also independent of any other order.

 Array of truth

Array 在 Javascript 中是一个对象, Array 的索引是属性名。事实上, Javascript 中的 “array” 有些误导性, Javascript 中的 Array 并不像大部分其他语言的数组。首先, Javascript 中的 Array 在内存上并不连续,其次, Array 的索引并不是指偏移量。实际上, Array 的索引也不是 Number 类型,而是 String 类型的。我们可以正确使用如 arr[0] 的写法的原因是语言可以自动将 Number 类型的 0 转换成 String 类型的 "0" 。所以,在 Javascript 中从来就没有 Array 的索引,而只有类似 "0" 、 "1" 等等的属性。有趣的是,每个 Array 对象都有一个 length 的属性,导致其表现地更像其他语言的数组。但为什么在遍历 Array 对象的时候没有输出 length 这一条属性呢?那是因为 for-in 只能遍历“可枚举的属性”, length 属于不可枚举属性,实际上, Array 对象还有许多其他不可枚举的属性。

 

现在,我们再回过头来看看用 for-in 来循环数组的例子,我们修改一下前面遍历数组的例子:

 

 

运行结果是:

 

 

 

我们看到 for-in 循环访问了我们新增的 "name" 属性,因为 for-in 遍历了对象的所有属性,而不仅仅是“索引”。同时需要注意的是,此处输出的索引值,即 "0"、 "1"、 "2"不是 Number 类型的,而是 String 类型的,因为其就是作为属性输出,而不是索引。那是不是说不在我们的 Array 对象中添加新的属性,我们就可以只输出数组中的内容了呢?答案是否定的。因为 for-in 不仅仅遍历 array 自身的属性,其还遍历 array 原型链上的所有可枚举的属性。下面我们看个例子:

 

 

运行结果是:

Guess you like

Origin www.cnblogs.com/zhouyideboke/p/12092870.html