var arr = ['a','b','c','d'];
// 使用for..in
for (var i in arr) {
console.log('索引:' + i + ',值:' + arr[i]);
}
使用for循环
var j = 0; j < arr.length; j++) {
console.log('索引:' + j + ',值:' + arr[j]);
}
/* 两种方式都输出:
* ----------------
* 索引:0,值:a
* 索引:1,值:b
* 索引:2,值:c
* 索引:3,值:d
* ----------------
*/
var colors = ['red','green','blue'];
扩展Array.prototype
Array.prototype.demo = function () {};
colors) {
console.log(i); 输出: 0 1 2 demo
}
查看原生的方法[[enumberable]]特征,这里以splice为例
Array.prototype.propertyIsEnumerable('splice'); false
Object.getOwnPropertyDescriptor(Array.prototype,'splice'); {writable: true,enumerable: false,configurable: true}
查看 demo 属性的特性
Array.prototype.propertyIsEnumerable('demo'); true
Object.getOwnPropertyDescriptor(Array.prototype,'demo'); Object.defineProperty()
来定义属性,此外如果浏览器版本不支持ES5的话,我们可以使用hasOwnProperty()
方法在for..in代码块内将可枚举的属性过滤掉。
];
Object.defineProperty(Array.prototype,'demo',{
enumerable: false() {}
});
Array.prototype.propertyIsEnumerable('demo'); {writable: false,configurable: false}
输出:0 1 2
或者使用 hasOwnProperty
];
Array.prototype.demo = () {};
安全使用hasOwnProperty方法
var hasOwn = Object.prototype.hasOwnProperty;
colors) {
if (hasOwn.call(colors,i)) {
console.log(i); }
}
遍历数组
];
colors.length = 10;
colors.push('yellow');
Array.prototype.demo = () {};
Object.keys(colors); 0 1 2 10
遍历对象
Person(name,age) {
this.name = name;
this.age = age;
}
Person.prototype.demo = var jenemy = new Person('jenemy',25);
Object.keys(jenemy); name age
在 ES5 环境
Object.keys('foo'); TypeError: "foo" is not an object
在 ES6 环境
Object.keys('foo'); ["0","1","2"]
传入 null 对象
Object.keys(null); Uncaught TypeError: Cannot convert undefined or null to object
传入 undefined
Object.keys(undefined); Uncaught TypeError: Cannot convert undefined or null to object
From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
if (!Object.keys) {
Object.keys = (() {
'use strict';
Object.prototype.hasOwnProperty,hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString'),dontEnums = [
'toString''valueOf''isPrototypeOf''constructor'
],dontEnumsLength = dontEnums.length;
return (obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [],prop,i;
for (prop obj) {
(hasOwn.call(obj,prop)) {
result.push(prop);
}
}
(hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
return result;
}
}) ();
}
A(a,aa) {
this.a = a;
this.aa = aa;
this.getA = () {
this.a;
}
}
原型方法
A.prototype.aaa = var B = new A('b','bb');
B.myMethodA = () {};
不可枚举方法
Object.defineProperty(B,'myMethodB'() {}
});
Object.getOwnPropertyNames(B); ["a","aa","getA","myMethodA","myMethodB"]