首页 > 解决方案 > 为什么我无法在客户对象中返回此特定键的值?

问题描述

应该返回 true 但它是未定义的,我不知道为什么。

function coffeeLoverExtended(customer){
  for (var key in customer) {
    return customer[key]['enjoysCoffee'];
  }
}

var customer001 = {
  name: "John Riley",
  ticketNumber: "A01",
  enjoysCoffee: true
};

console.log(coffeeLoverExtended(customer001)); //true

标签: javascript

解决方案


你正在做的是循环一个对象customer并一个一个地获取密钥。key包含customer对象中的属性。那么什么customer[key]['enjoysCoffee']意味着get me the enjoysCoffee property from customer[key]key 是对象的属性之一customer

没有对象enjoysCoffee的属性customer[enjoysCoffee]。这就是它返回的原因undefined

如果您试图获取enjoysCoffee对象的属性值customer。那么它应该是customer["enjoysCoffee"]

function coffeeLoverExtended(customer) {
  return customer["enjoysCoffee"];
}

var customer001 = {
  name: "John Riley",
  ticketNumber: "A01",
  enjoysCoffee: true,
};

console.log(coffeeLoverExtended(customer001)); //true

您必须使用.[]访问对象的属性。如果你写customer["enjoysCoffee"]customer.enjoysCoffee

下面是嵌套对象示例

function coffeeLoverExtended(customer) {
  // return customer.enjoysCoffeeObj["enjoysCoffee"];
  // or
  // return customer["enjoysCoffeeObj"].enjoysCoffee;
  // or
  // return customer["enjoysCoffeeObj"]["enjoysCoffee"];
  // or
  return customer.enjoysCoffeeObj.enjoysCoffee;
}

var customer001 = {
  name: "John Riley",
  ticketNumber: "A01",
  enjoysCoffeeObj: {
    enjoysCoffee: true,
  },
};

console.log(coffeeLoverExtended(customer001)); //true

以上所有的 return 语句都返回true


推荐阅读