1. 数组
1.1 for i++
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] for (var i = 0, l = arr.length; i < l; i++) { console.log(i, arr[i]) }
输出:
1.2 for l--
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] for (var l = arr.length; l--;) { console.log(l, arr[l]) }
输出:
应用:
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] for (var l = arr.length; l--;) { arr.splice(l, 1) } console.log(arr) // []
1.3 while l--
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] var l = arr.length while(l--) { console.log(l, arr[l]) }
输出:
2.对象
var obj = {one: 1, two: 2, three: 3} for (var key in obj) { console.log(key, obj[key]) }
输出:
3. ES5
var arr = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] arr.forEach(function(value, index, array) { console.log(index, value, array) })
输出:
4. Underscore.js
<script src="underscore.js"></script> <script> var list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] _.each(list, function(element, index, list) { console.log(element, index, list, this) }, list) _.each({one: 1, two: 2, three: 3}, function(value, key, list) { console.log(value, key, list) }) </script>
输出:
5. jQuery
<script src="jquery-1.10.2.js"></script> <script> var list = ['a', 'b', 'c', 'd', 'e', 'f', 'g'] $.each(list, function(index, value) { console.log(index, value) }) $.each({one: 1, two: 2, three: 3}, function(key, value) { console.log(key, value) }) </script>
输出:
6.Angular
angular.forEach(['a', 'b'], function(value, index) { console.log(value, index) }) angular.forEach({a: 1, b: 2}, function(value, key) { console.log(value, key) })
7.Python
info = ['a','b','c','d','ee','fff'] for m in info: print m
for in
Object.prototype.bar = 1 var foo = {goo: undefined} for (var p in foo) { console.log(p) // goo bar if (foo.hasOwnProperty(p)) { console.log('hasOwnProperty', p) // goo } }