假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
假设我这样创建一个对象:
var myObject =
{"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"};
检索属性名列表的最佳方法是什么?例如,我想以一些变量“键”结束,这样:
keys == ["ircEvent", "method", "regex"]
当前回答
在现代浏览器(IE9+, FF4+, Chrome5+, Opera12+, Safari5+)中,您可以使用内置的Object。键的方法:
var keys = Object.keys(myObject);
上面有一个完整的填充,但一个简化的版本是:
var getKeys = function(obj){
var keys = [];
for(var key in obj){
keys.push(key);
}
return keys;
}
或者将var getKeys替换为object. prototype.keys,以允许你在任何对象上调用.keys()。扩展原型有一些副作用,我不建议这么做。
其他回答
Mozilla有完整的实现细节,关于如何在不支持它的浏览器中实现它,如果这有帮助的话:
if (!Object.keys) {
Object.keys = (function () {
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),
dontEnums = [
'toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'
],
dontEnumsLength = dontEnums.length;
return function (obj) {
if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');
var result = [];
for (var prop in obj) {
if (hasOwnProperty.call(obj, prop)) result.push(prop);
}
if (hasDontEnumBug) {
for (var i=0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);
}
}
return result;
};
})();
}
你可以把它包括在你喜欢的任何地方,但可能是在脚本堆栈顶部的某种extensions.js文件中。
使用Reflect.ownKeys ()
var obj = {a: 1, b: 2, c: 3};
Reflect.ownKeys(obj) // ["a", "b", "c"]
对象。键和对象。getOwnPropertyNames不能获得不可枚举的属性。它甚至适用于不可枚举的属性。
var obj = {a: 1, b: 2, c: 3};
obj[Symbol()] = 4;
Reflect.ownKeys(obj) // ["a", "b", "c", Symbol()]
我是转储功能的超级粉丝。
ajax»JavaScript变量转储在Coldfusion
下载转储功能
解决方案工作在我的情况和跨浏览器:
var getKeys = function(obj) {
var type = typeof obj;
var isObjectType = type === 'function' || type === 'object' || !!obj;
// 1
if(isObjectType) {
return Object.keys(obj);
}
// 2
var keys = [];
for(var i in obj) {
if(obj.hasOwnProperty(i)) {
keys.push(i)
}
}
if(keys.length) {
return keys;
}
// 3 - bug for ie9 <
var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');
if(hasEnumbug) {
var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',
'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];
var nonEnumIdx = nonEnumerableProps.length;
while (nonEnumIdx--) {
var prop = nonEnumerableProps[nonEnumIdx];
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
keys.push(prop);
}
}
}
return keys;
};
可以用jQuery这样做:
var objectKeys = $.map(object, function(value, key) {
return key;
});