var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
console.log(propt + ': ' + obj[propt]);
}
propt
如何表示对象的属性?它不是内置方法或属性。为什么它出现在对象的每个属性中?< /p>
var obj = {
name: "Simon",
age: "20",
clothing: {
style: "simple",
hipster: false
}
}
for(var propt in obj){
console.log(propt + ': ' + obj[propt]);
}
propt
如何表示对象的属性?它不是内置方法或属性。为什么它出现在对象的每个属性中?< /p>
hasOwnProperty
检查:for (var prop in obj) {
if (Object.prototype.hasOwnProperty.call(obj, prop)) {
// do stuff
}
}
这是必要的,因为对象的原型包含了技术上属于该对象的其他属性。这些附加属性是从基本对象类继承而来的,但仍然是obj
的属性。
hasOwnProperty
只是检查这是否是特定于此类的属性,而不是从基类继承的属性。
也可以通过对象本身调用hasOwnProperty
:
if (obj.hasOwnProperty(prop)) {
// do stuff
}
但是,如果对象具有相同名称的不相关字段,则此操作将失败:
var obj = { foo: 42, hasOwnProperty: 'lol' };
obj.hasOwnProperty('foo'); // TypeError: hasOwnProperty is not a function
Object.prototype
进行调用的原因:var obj = { foo: 42, hasOwnProperty: 'lol' };
Object.prototype.hasOwnProperty.call(obj, 'foo'); // true
Object.prototype
,否则该循环不会显示任何继承属性。这可能是好建议,但你自己说过“我无法理解‘循环遍历对象属性’”。许多人选择不添加 hasOwnProperty
检查。如果你自己创建了对象,并且没有添加一些愚蠢的库来添加属性到 Object.Prototype
,那么就不需要进行此类检查。 - Ruan Mendesproperty
应当被称为propertyName
,因为property
是一个字符串。否则会让像我这样的JS新手感到困惑,即不知道在if
语句内该做什么。 - Victor Zakharov从JavaScript 1.8.5开始,您可以使用Object.keys(obj)
来获取在对象本身上定义的属性数组(那些对于obj.hasOwnProperty(key)
返回true的属性)。
Object.keys(obj).forEach(function(key,index) {
// key: the name of the object key
// index: the ordinal position of the key within the object
});
使用 Object.keys()
比使用 for-in 循环更好(且更易读)。
以下浏览器支持该方法:
有关更多信息,请参阅 Mozilla 开发者网络的 Object.keys() 参考文档。
Object.keys(myObject).forEach(function(key,index) {
//key = 对象键的名称
//index = 键在对象中的序列位置
});
- Todd Price各位女士和男士,我们已经进入了2019年,没有太多时间来打字......因此让我们使用这个酷炫的新型ECMAScript 2016:
Object.keys(obj).forEach(e => console.log(`key=${e} value=${obj[e]}`));
window.performance.memory
仅被 Chrome 支持,而 Object.keys(obj)
返回一个空数组。这与 .map
无关。 - Frank Rothe
来做多个事情,可以参考我发布的这个 gist。它基本上就像大多数哈希实现一样,使用 (
(key)
=>
(value)
)
而不是 {
key
=>
value
}
,但如果你以前没有处理过这种情况,它可能会帮助你更好地理解:https://gist.github.com/the-nose-knows/9f06e745a56ff20519707433e28a4fa8 - kayleeFrye_onDeck在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 (const [key, value] of Object.entries(obj)) { }
。 - OzzyCzech这是 for...in语句
(MDN, ECMAScript规范)。
你可以把它理解为“对于对象 obj
中的每个属性, 将每个属性依次赋值给变量 PROPT ”。
in
运算符和for
语句并不参与其中,for-in
语句是一种独立的语法结构:for ( LeftHandSideExpression in Expression )
,for ( var VariableDeclarationNoIn in Expression )
。 - Christian C. Salvadó这只是一个 for...in
循环。请查看 Mozilla 的文档。
if (typeof obj === 'object' && obj !== null) {
Object.keys(obj).forEach(key => {
console.log("\n" + key + ": " + obj[key]);
});
}
// *** Explanation line by line ***
// Explaining the bellow line
// It checks if obj is neither null nor undefined, which means it's safe to get its keys.
// Otherwise it will give you a "TypeError: Cannot convert undefined or null to object" if obj is null or undefined when it tries to get its keys in the next line of code.
// NOTE 1: You can use Object.hasOwnProperty() instead of Object.keys(obj).length
// NOTE 2: No need to check if obj is an array because it will work just fine.
// NOTE 3: No need to check if obj is a string because it will not pass the 'if typeof obj is Object' statement.
// NOTE 4: No need to check if Obj is undefined because it will not pass the 'if type obj is Object' statement either.
if (typeof obj === 'object' && obj !== null) {
// Explaining the bellow line
// Just like in the previous line, this returns an array with
// all keys in obj (because if code execution got here, it means
// obj has keys.)
// Then just invoke built-in javascript forEach() to loop
// over each key in returned array and calls a call back function
// on each array element (key), using ES6 arrow function (=>)
// Or you can just use a normal function ((key) { blah blah }).
Object.keys(obj).forEach(key => {
// The bellow line prints out all keys with their
// respective value in obj.
// key comes from the returned array in Object.keys(obj)
// obj[key] returns the value of key in obj
console.log("\n" + key + ": " + obj[key]);
});
}
forEach
跳过空值,因此我认为您可以摆脱if语句,只需像Frank Roth的答案一样执行Object.keys(obj).forEach(e => console.log(\
key=${e} value=${obj[e]}`));`。 - Darkproduct如果您的环境支持ES2017,我会建议使用Object.entries:
Object.entries(obj).forEach(([key, value]) => {
console.log(`${key} ${value}`);
});
如Mozilla的Object.entries()文档所示:
Object.entries()方法返回一个给定对象自身可枚举属性[key, value]对的数组,顺序与使用for...in循环(不同之处在于for-in循环也会枚举原型链中的属性)提供的顺序相同。
简单来说,使用Object.entries我们可以省略使用旧的for...in循环所需的额外步骤:
// This step is not necessary with Object.entries
if (object.hasOwnProperty(property)) {
// do stuff
}
Dominik的答案是完美的,我只是更喜欢这种方式来做,因为它更容易阅读:
for (var property in obj) {
if (!obj.hasOwnProperty(property)) continue;
// Do stuff...
}
object
。 - shrekuu现在,jQuery可以让您做到这一点:
$.each( obj, function( key, value ) {
alert( key + ": " + value );
});