- for
var myArray = [1,2,3]; for (var i = 0; i < myArray.length; i++) { alert(myArray[i]); }
output
--------------------------------------------
1
2
3
- for in
var obj = { a : 1, b : 2 }; for(var key in obj) { alert(key); }
output
--------------------------------------------
a
b
- forEach (IE9 之後才支援)
forEach 是從 Array.prototype.forEach 來的, 因此只要是 Array 物件就擁有 forEach 方法
function alertElements(element, index, array) { alert(element); } [1,2,3].forEach(alertElements);
output
--------------------------------------------
1
2
3
在 ECMAScript 5, 也可使用 forEach 取得物件屬性名稱
var obj = { a : 1, b : 2 }; Object.keys(obj).forEach(function(key) { alert(key); });
output
--------------------------------------------
a
b
- while
var i=0; var myArray = [1,2,3]; while(myArray[i]) { alert(myArray[i]); i++; }
output
--------------------------------------------
1
2
3
- do while
var i = 1; var sum = 0; do { sum += i; i++; } while (i <= 100); alert(sum);
output
--------------------------------------------
5050
7/07/2013
Subscribe to:
Post Comments (Atom)
0 comments:
Post a Comment