不要使用for (key in obj)
,它将迭代所有可枚举属性,包括原型属性,并可能导致令人惊讶的可怕事情。现代 JS 有一个特殊的函数,可以仅从对象中获取相关的键,使用对象.keys(...) https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys,所以如果你使用var keys = Object.keys(obj)
要将键列表作为数组获取,您可以对其进行迭代:
// blind iteration
Object.keys(obj).forEach(function(key, i) {
var value = obj[key];
// do what you need to here, with index i as position information.
// Note that you cannot break out of this iteration, although you
// can of course use ".some()" rather than ".forEach()" for that.
});
// indexed iteration
for(var keys = Object.keys(obj), i = 0, end = keys.length; i < end; i++) {
var key = keys[i], value = obj[key];
// do what you need to here, with index i as position information,
// using "break" if you need to cut the iteration short.
});
或立即选择其最后一个元素
var keys = Object.keys(obj);
var last = keys[keys.length-1];
或使用slice https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice:
var keys = Object.keys(obj);
var last = keys.slice(-1)[0];
或使用shift https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/shift(但这是一个破坏性的操作,所以我们不会缓存键,因为移位将其变成“不再是所有键”):
var last = Object.keys(obj).shift();
2021年编辑
现在还有对象.条目 https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/entries函数,它可以一次性获取键/值对:
Object.entries(obj).forEach(([key, value]) => {
console.log(`key "${key}" points to:`, value):
});