我有一个 JavaScript 对象,例如
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
}
如何获取此对象中键的长度和列表?
我有一个 JavaScript 对象,例如
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
}
如何获取此对象中键的长度和列表?
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
}
var keys = Object.keys(obj);
console.log('obj contains ' + keys.length + ' keys: '+ keys);
现在大多数主要浏览器都支持它。
var obj = {
key1: 'value1',
key2: 'value2',
key3: 'value3',
key4: 'value4'
};
var keys = [];
for (var k in obj) keys.push(k);
console.log("total " + keys.length + " keys: " + keys);
Underscore.js 使转换非常干净:
var keys = _.map(x, function(v, k) { return k; });
编辑:我错过了你也可以这样做:
var keys = _.keys(x);
如果您只想要特定于该特定对象的键而不是任何派生prototype
属性:
function getKeys(obj) {
var r = []
for (var k in obj) {
if (!obj.hasOwnProperty(k))
continue
r.push(k)
}
return r
}
例如:
var keys = getKeys({'eggs': null, 'spam': true})
var length = keys.length // access the `length` property as usual for arrays
var keys = new Array();
for(var key in obj)
{
keys[keys.length] = key;
}
var keyLength = keys.length;
要访问对象中的任何值,您可以使用 obj[key];