for...in循环、for each...in循环的区别
for...in循环:
for...in语句用来迭代(或者说遍历)对象的属性或数组中的元素,并对每个属性或方法执行运算。但是对象的方法不能由for...in语句来迭代,有些语句也不能有for...in来迭代,例如某些宿主对象的属性。和实力成员不同的是,静态成员也是不能迭代的。
例子:
1、用for...in语句遍历myObject对象的属性:
var myObject = {hisName: "javascript", age: 11, belonging: "ECMA" }; for(var prop in myObject){ document.write("myObject." + prop + "=" myObject[prop] + "<br>"); }
执行的结果将会显示在浏览器中,如下:
myObject.hisName = javascript myObject.belonging = ECMA myObject.age = 11
2、下面用for...in语句遍历数组的元素:
var myArray = new Array("one","two","three"); for(var index in myArray){ document.write("myArray[" + index + "] = " + myArray[index] + "<br>"): }
执行的结果将会显示在浏览器中,如下:
myArray[2] = three myArray[1] = two myArray[0] = one
for each...in :
与for...in语句不同的是,for each...in语句将遍历对象属性的值,而不是属性的名称。
例子:
1、用for each...in语句遍历myObject对象的属性:
var myObject = {hisName: "javascript", age: 11, belonging: "ECMA" }; for(var item in myObject){ document.write(item+ "<br>"); }
执行的结果将会显示在浏览器中,如下:
javascript ECMA 11
2、下面用for each...in 语句遍历数组的元素:
var myArray = new Array("one","two","three"); for(var item in myArray){ document.write(item + "<br>"): }
执行的结果将会显示在浏览器中,如下:
three two one
相关推荐
LowisLucifer 2020-06-05
JamesRayMurphy 2020-05-31
tengyuan 2020-04-25
zhaobig 2020-08-17
xiaonamylove 2020-08-16
CloudXli 2020-08-14
LowisLucifer 2020-08-09
yawei 2020-07-06
zlfing 2020-07-07
徐建岗网络管理 2020-06-09
Jieen 2020-05-18
zyazky 2020-05-17
sdwylry 2020-05-14
sucheng 2020-05-09
sdwylry 2020-04-27
huakai 2020-02-25
Ericbig 2020-02-25
yunfenglee 2020-02-02