for ... in (枚举)
var obj = {
a: 1,
b: [],
c: function () {}
};
for (var key in obj) {
console.log(key);
}
输出结果:a b c
var arr = [3, 5, 7];
for (var i in arr) {
console.log(i);
}
输出结果:0 1 2
var arr = [3, 5, 7];
for (var i in arr) {
console.log(i, arr[i]);
}
输出结果:0 3 1 5 2 7
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
var arr = [3, 5, 7];
arr.foo = 'hello';
for (var i in arr) {
console.log(i);
}
输出结果:0 1 2 foo arrCustom objCustom
hasOwnProperty: 判断对象是否包含特定的自身(非继承)属性
Object.prototype.objCustom = function() {};
Array.prototype.arrCustom = function() {};
var arr = [3, 5, 7];
arr.foo = 'hello';
for (var i in arr) {
if (arr.hasOwnProperty(i)) {
console.log(i);
}
}
for ... of (迭代)
var arr = [3, 5, 7];
for (var i of arr) {
console.log(i);
}
输出结果:3 5 7
张鑫旭——for...in/for...of