For most objects, use for .. in
:
(对于大多数对象, for .. in
:)
for (let key in yourobject) {
console.log(key, yourobject[key]);
}
With ES6, if you need both keys and values simultaneously, do
(使用ES6,如果同时需要键和值,请执行)
for (let [key, value] of Object.entries(yourobject)) {
console.log(key, value);
}
To avoid logging inherited properties, check with hasOwnProperty :
(为了避免记录继承的属性,请使用hasOwnProperty进行检查:)
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) {
console.log(key, yourobject[key]);
}
}
You don't need to check hasOwnProperty
when iterating on keys if you're using a simple object (for example one you made yourself with {}
).
(如果您使用的是简单对象(例如,您使用{}
对象),则在对键进行迭代时无需检查hasOwnProperty
。)
This MDN documentation explains more generally how to deal with objects and their properties.
(该MDN文档更一般地说明了如何处理对象及其属性。)
If you want to do it "in chunks", the best is to extract the keys in an array.
(如果要“分块”执行,最好的方法是将键提取到数组中。)
As the order isn't guaranteed, this is the proper way.(由于不能保证顺序,这是正确的方法。)
In modern browsers, you can use(在现代浏览器中,您可以使用)
let keys = Object.keys(yourobject);
To be more compatible, you'd better do this :
(为了更加兼容,您最好这样做:)
let keys = [];
for (let key in yourobject) {
if (yourobject.hasOwnProperty(key)) keys.push(key);
}
Then you can iterate on your properties by index: yourobject[keys[i]]
:
(然后,您可以通过索引迭代属性: yourobject[keys[i]]
:)
for (let i=300; i < keys.length && i < 600; i++) {
console.log(keys[i], yourobject[keys[i]]);
}