如何在Javascript中获取对象的属性?

时间:2016-06-05 07:41:34

标签: javascript object

从Codecademy学习。我必须将对象的属性赋予变量(不是属性值)。这让我的脑子在一小时内搞砸了。

这是代码(我搞砸了一点找到解决方案。请使用评论正确理解。我很困惑) SCREENSHOT:http://prntscr.com/bcj94x

var james = {
job: "programmer",
married: false
};

// set to the first property name of "james"
var aProperty = james["job"];

// print the value of the first property of "james" 
// using the variable "aProperty"
console.log(james["job"]);
console.log(aProperty);

我得到:这在运行脚本

时在控制台中
programmer 
programmer 

由于

3 个答案:

答案 0 :(得分:1)

您期望得到什么结果?

使用Javascript对象表示法(简称JSON)定义对象会导致对象具有两个属性jobmarried

此对象通过变量james引用。每次在代码中使用james时,您都在处理引用的对象。

var aProperty = james["job"];也是如此。每次使用变量aProperty时,它都会引用job引用的对象的james属性。

这就像说:»从现在开始,当我说“aProperty”时,我指的是james«的工作属性。

您的评论有点误导:

  

//设置为“james”的第一个属性名称

在这种情况下,job第一个属性。正确的是set to the property named job

从上面来看,结果应该不会出乎意料。

console.log(james["job"]);
console.log(aProperty);

同时打印programmer,因为aProperty等同于james["job"],例如Thomasthe person who wrote this引用me,因此相当于<input type="password" ng-model="dataItem.password" class="form-control" name="password" placeholder="Enter Password" value=" "/>

答案 1 :(得分:0)

如果要获取与给定值关联的键,可以执行以下操作:

var james = {
  job: "programmer",
  married: false
};

Object.prototype.getKey = function (value){
  for(var property in this){
     if(this.hasOwnProperty(property)) {
          if(this[property] === value )
              return property;
          }
     }
};

console.log(james.getKey('programmer'));

它会给你“工作”。

因此,使用此功能,您只需编写:

 var aProperty = james.getKey('programmer');

答案 2 :(得分:0)

您可以使用onCreateContextMenu()循环将 james 对象中找到的onContextItemSelected()对的for in值放入名为 aProperty的数组中,然后在控制台中打印出结果。

key