一、周遊對象方法
1.for...in
周遊輸出的是對象自身的屬性以及原型鍊上可枚舉的屬性(不含Symbol屬性),原型鍊上的屬性最後輸出說明先周遊的是自身的可枚舉屬性,後周遊原型鍊上的
eg:

var obj = { 'name': "yayaya", 'age': '12', 'sex': 'female' };
Object.prototype.pro1 = function() {};//在原型鍊上添加屬性
Object.defineProperty(obj, 'country', {
Enumerable: true //可枚舉
});
Object.defineProperty(obj, 'nation', {
Enumerable: false //不可枚舉
})
obj.contry = 'china';
for (var index in obj) {
console.log('key=', index, 'value=', obj[index])
}

輸出結果:
key = name value = yayaya
key = age value = 12
key = sex value = female
key = contry value = china
key = pro1 value = function(){}
2.Object.keys()
周遊對象傳回的是一個包含對象自身可枚舉屬性的數組(不含Symbol屬性).

var obj = { 'name': "yayaya", 'age': '12', 'sex': 'female' };
Object.prototype.pro1 = function() {}
Object.defineProperty(obj, 'country', {
Enumerable: true,
value: 'ccc'
});
Object.defineProperty(obj, 'nation', {
Enumerable: false //不可枚舉
})
obj.contry = 'china';
Object.keys(obj).forEach(function(index) {
console.log(index, obj[index])
});

name yayaya
age 12
sex female
contry china
3.Objcet.getOwnPropertyNames()
輸出對象自身的可枚舉和不可枚舉屬性的數組,不輸出原型鍊上的屬性

var obj = { 'name': "yayaya", 'age': '12', 'sex': 'female' };
Object.prototype.pro1 = function() {}
Object.defineProperty(obj, 'country', {
Enumerable: true,
value: 'ccc'
});
Object.defineProperty(obj, 'nation', {
Enumerable: false //不可枚舉
})
obj.contry = 'china';
Object.getOwnPropertyNames(obj).forEach(function(index) {
console.log(index, obj[index])
});

country ccc
nation undefined
4.Reflect.ownKeys()
傳回對象自身的所有屬性,不管屬性名是Symbol或字元串,也不管是否可枚舉.

var obj = { 'name': "yayaya", 'age': '12', 'sex': 'female' };
Object.prototype.pro1 = function() {}
Object.defineProperty(obj, 'country', {
Enumerable: true,
value: 'ccc'
});
Object.defineProperty(obj, 'nation', {
Enumerable: false //不可枚舉
})
obj.contry = 'china';
Reflect.ownKeys(obj).forEach(function(index) {
console.log(index, obj[index])
});

傳回結果:
5. _.keys
用underscore插件的周遊方法隻可以周遊出對象自身的可枚舉屬性

var obj = { 'name': "yayaya", 'age': '12', 'sex': 'female' };
Object.prototype.pro1 = function() {}
Object.defineProperty(obj, 'country', {
Enumerable: true,
value: 'ccc'
});
Object.defineProperty(obj, 'nation', {
Enumerable: false //不可枚舉
})
obj.contry = 'china';
console.log(_.keys(obj));

name age sex country
二.周遊數組方法
1.forEach(無法使用break中斷)
var arr = ['a', 'b', 'c', 'd'];
arr.forEach(function(value, index) {
console.log('value=', value, 'index=', index);
})
value=a index=0
value=b index=1
value=c index=2
value=d index=3
2.map(可以使用break中斷)
可以對周遊的每一項做相應的處理,傳回每次函數調用的結果組成的數組
var arr = ['a', 'b', 'c', 'd'];
arr.map(function(item, index, array) {
console.log(item, index);
})
a 0
b 1
c 2
d 3
3.for循環周遊
var arr = ['a', 'b', 'c', 'd'];
for (var i = 0; i < arr.length; i++) {
console.log(i, arr[i])
}
0 a
1 b
2 c
3 d
4.for...in(雖然也可以周遊數組,但是此方法一般用于周遊對象)
var arr = ['a', 'b', 'c', 'd'];
for (var i in arr) {
console.log('index:', i, 'value:', arr[i])
}
var arr = ['a', 'b', 'c', 'd'];
for (var value of arr) {
console.log('value', value)
}
窮則獨善其身,達則兼濟天下……