天天看点

【遍历】

  • ​​如何在Array.forEach的循环里break​​
  • ​​【underscore.js 源码解读】for ... in 存在的浏览器兼容问题你造吗​​

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

​​python list遍历​​

info = ['a','b','c','d','ee','fff']
for m in info:
    print m      

for in

​​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
    }
}      
下一篇: 遍历