Javascript 中的for…in…循環

JavaScript提供一種特殊的循環,用於單步執行對象的所有用戶定義的屬性或數組的所有元素。for...in循環中的循環計數器是字符串,而不是數字。它包含當前屬性的名稱或當前數組元素的索引。

// Create an object with some properties
var myObject = new Object();
myObject.name = "James";
myObject.age = "22";
myObject.phone = "555 1234";
// Enumerate (loop through)_all the properties in the object
for (var prop in myObject)
{
// This displays "The property 'name' is James", etc..
document.write("The property '" + prop + "' is " + myObject[prop]);
// New line.
document.write("<br />");
}

雖然for...in循環看起來類似於VBScript的ForEach...Next循環,但二者的工作方式不同。JavaScriptfor...in循環將循環訪問JavaScript對象的屬性。VBScriptForEach...Next循環將循環訪問集合中的項(C#中的for…in…循環也是遍歷集合的)。若要循環JavaScript中的集合,您需要使用Enumerator對象。雖然某些對象(如InternetExplorer中的對象)同時支持VBScriptForEach...Next循環和JavaScriptfor...in循環,但大多數對象都無法實現這一點。

上述代碼執行結果:

The property 'name' is James
The property 'age' is 22
The property 'phone' is 555 1234

本文出自 “獨釣寒江雪” 博客,請務必保留此出處http://zhaojie.blog.51cto.com/1768828/1310402

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章