javascript 中的for ----in 循环

<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>

posted on 2009-06-03 16:47  5201314  阅读(260)  评论(0编辑  收藏  举报

导航