javascript 中的for —-in 迴圈

來源:互聯網
上載者:User
<script>
//為一個對象的每個屬性,或一個數組或集合中的每個元素,執行一個或多個語句。
//for ( [var] variable in {object | array | collection})
/*variable

    必需。一個變數,可以是 object 的任何屬性名稱、array 的任何索引或 collection 的任何元素。

*/
function ForInDemo(){
   // 建立某些變數。
   var a, key, s = "";
   // 初始化對象。
   a = {"a" : "Athens" , "b" : "Belgrade", "c" : "Cairo"}
   // 迭代屬性。
   for (key in a)   {
      s += a[key] + "<br />";
   }
   return(s);
}
var t=ForInDemo();
alert (t);

function ok(aa,bb,cc){
 this.aa = aa
 this.bb = bb
 this.cc = cc
}
newemp = new ok("h1","h2","h3");//h1賦給了aa,h2賦給了bb,h3賦給了cc
document.write("我:"+ newemp.aa +"<br>");//輸出了aa,
document.write("你:"+ newemp.bb +"<br>");//輸出了bb
document.write("他:"+ newemp.cc);//輸出了cc

//用 for ----in  //屬性和值的  形式
function ok(aa,bb,cc){
this.aa = aa
this.bb = bb
this.cc = cc
}
newemp = new ok("我:h1<br>","你:h2<br>","他:h3<br>");
for(x in newemp)//迴圈一個對象newemp, x為屬性:屬性分別為:aa bb cc 值分別為:我:h1<br>  你:h2<br> 他:h3<br>
document.write(newemp[x]);

//手冊中!!
// Create an object with some properties.
var prop, myObject = new Object();
myObject.name = "James";
myObject.age = 22;
myObject.phone = "555 1234";
// Loop through all the properties in the object.
for (prop in myObject){
   print("myObject." + prop + " equals " + myObject[prop]);
}

function ForInDemo1() {
   var ret = "";

   // Initialize the object with properties and values.
   var obj : Object = {"a" : "Athens" ,
                       "b" : "Belgrade",
                       "c" : "Cairo"};

   // Iterate over the properties.
   for (var key in obj)
      // Loop and assign 'a', 'b', and 'c' to key.
      ret += key + ":\t" + obj[key] + "\n";

   return(ret);
} // ForInDemo1
</script>

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.