javascript - 为什么我无法在客户对象中返回此特定键的值?
问题描述
应该返回 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
解决方案
你正在做的是循环一个对象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
。
推荐阅读
- python - Python 代码无法运行,我不知道如何修复它
- powershell - 自定义输出 Get-fsrmQuota 报告
- primefaces - 多次调用 LazyDataModel 初始加载
- javascript - Angular - 将具有页面大小的值传递给另一个组件 - currentValue undefined 错误
- newrelic - 具有新遗物集成的 Quarkus (javaagent)
- android - 谁将 touchEvent 传递给 Activity?
- excel - 如何用某个范围内的公式填充一列
- java - 使用java中的流编写/创建具有3个唯一随机数的int []的最短方法是什么?
- python - 我可以将一个数组中的特定值附加到另一个数组吗?
- reactjs - 在 gatsby-transformer-remark 的 graphql 查询中使用 OR 条件