var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
console.log(propt + ': ' + obj[propt]);
}
变量如何propt表示对象的属性?它不是内置方法或属性。为什么它包含对象中的每个属性?
var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
console.log(propt + ': ' + obj[propt]);
}
变量如何propt表示对象的属性?它不是内置方法或属性。为什么它包含对象中的每个属性?
Your for loop is iterating over all of the properties of the object obj. propt is defined in the first line of your for loop. It is a string that is a name of a property of the obj object. In the first iteration of the loop, propt would be "name".
Objects in JavaScript are collections of properties and can therefore be looped in a for each statement.
You should think of obj as an key value collection.
Object.keys(obj).forEach(key =>
console.log(`key=${key} value=${obj[key]}`)
);
您可以使用Lodash。该文件
var obj = {a: 1, b: 2, c: 3};
_.keys(obj).forEach(function (key) {
...
});
let obj = {"a": 3, "b": 2, "6": "a"}
Object.keys(obj).map((item) => {console.log("item", obj[item])})
// a
// 3
// 2
jQuery允许您立即执行此操作:
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});
Dominik的答案很完美,我只喜欢那样做,因为它更容易阅读:
for (var property in object) {
if (!object.hasOwnProperty(property)) continue;
// Do stuff...
}
如果您的环境支持ES2017,那么我建议使用Object.entries:
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});
如Mozillas Object.entries()文档所示:
所述Object.entries()方法返回在给定对象的自己的可枚举的属性[键,值]对的数组,在相同的顺序,通过提供一种用于... in循环(不同之处在于一个用于-in循环枚举原型链中的属性)。
基本上使用Object.entries,我们可以放弃旧的for ... in循环所需的以下额外步骤:
// This step is not necessary with Object.entries
if (object.hasOwnProperty(property)) {
// do stuff
}
在ES的最新实现中,您可以使用Object.entries:
for (const [key, value] of Object.entries(obj)) { }
要么
Object.entries(obj).forEach(([key, value]) => ...)
如果只想遍历值,请使用Object.values:
for (const value of Object.values(obj)) { }
要么
Object.values(obj).forEach(value => ...)
这只是一个for...in循环。查看Mozilla上的文档。
这是for...in statement(MDN,ECMAScript spec)。
你可以把它读作“ FOR每个属性IN的obj对象,每个属性分配给PROPT依次变量”。
我们现在处于2019年的男女生中,我们没有太多的时间来打字...所以,让我们来做一下这个很酷的新奇ECMAScript 2016:
Object.keys(obj).forEach(e => console.log(`key=${e} value=${obj[e]}`));
从JavaScript 1.8.5开始,您可以Object.keys(obj)用来获取在对象本身上定义的属性数组(为返回true的属性obj.hasOwnProperty(key))。
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
这比使用for-in循环更好(更易读)。
这些浏览器支持它:
有关更多信息,请参见Mozilla开发人员网络Object.keys()的参考。
While the top-rated answer is correct, here is an alternate use case i.e if you are iterating over an object and want to create an array in the end. Use
.mapinstead offorEach