【问题标题】:In javascript, I have an array of objects. How do I console log the name of the object, rather than the contents? [duplicate]在 javascript 中,我有一个对象数组。如何控制台记录对象的名称,而不是内容? [复制]
【发布时间】:2017-08-05 10:51:21
【问题描述】:
jerry = {
  weight: 178

}

Malcom = {
  weight: 220
}

Bob = {
  Weight: 134

}

people = [jerry, Malcom, Bob]

console.log(people[0]);

我正在尝试获取对象名称“jerry”的 console.log。感谢您的帮助!

【问题讨论】:

  • 你不能;对象没有内部名称,一个对象可以有 50 个不同的 var 引用它...您可以在特定上下文中查找它并进行匹配,但这更像是一种巧合而不是一种方法。
  • 无需对此投反对票——这是新手可能不清楚的事情之一,因为一个人可能不具备理解问题的基本知识。
  • 在很多情况下,读者可能需要注意that assigning function objects to variables does preserve the variable name as a property。可以合理地想象标准对象可能具有相同的行为,但事实并非如此。
  • 这个话题不应该被关闭。它可以通过某种方式来完成,具体取决于对象是在哪个上下文中定义的。 Here 是一个工作示例。

标签: javascript arrays console.log


【解决方案1】:

ES6 版本: 使用Object#entriesArray#forEachdestructuring

const jerry = {weight: 178}
const Malcom = {weight: 178}
const Bob = {weight: 178}

const people = {jerry, Malcom, Bob}

const res = Object.entries(people).forEach(([name, {weight}])=>{
  console.log(name, weight);
});

你不能。 Jerry、Malcom 和 Bob 只是变量名,您有两个明显的解决方案:

为您的对象添加name 属性。

var jerry = {
 name: "jerry",
 weight: 178
}

或者把你的数组改成一个对象,然后用key作为你的对象的名字。

var people = {jerry: jerry, malcom: Malcom, bob: Bob}

例如:

var jerry = {
  weight: 178
}

var Malcom = {
  weight: 178
}

var Bob = {
  weight: 178
}

var people = {jerry: jerry, malcom: Malcom, bob: Bob}

for(var person in people){
  if(people.hasOwnProperty(person)){
    console.log(person, people[person].weight);
  }
}

【讨论】:

  • 反对者:嗯?他/她解释了为什么 OP 不能做他们想做的事,并提出了一个合理的选择。那怎么“没用”?
  • 赞成将人存储在对象中,并使用键代替名称。
  • 是的,我将使用一个对象来代替。非常感谢。
  • ES 2015:const people = { jerry, malcolm, bob };
【解决方案2】:

var Some = {
  MyValue : 1234
}
for (var i in Some) console.log(i);

var people = {
 jerry : { weight: 178 },
 Malcom : { weight: 220 },
 Bob : { weight: 134 }
}

for (var i in people) console.log( i +' : '+ people[i].weight )

【讨论】:

    猜你喜欢
    • 2015-10-13
    • 1970-01-01
    • 1970-01-01
    • 2018-07-31
    • 1970-01-01
    • 2023-03-18
    • 2022-01-12
    • 1970-01-01
    • 2012-02-23
    相关资源
    最近更新 更多