gpt4 book ai didi

javascript - 访问 Javascript 对象键

转载 作者:行者123 更新时间:2023-11-30 09:27:17 25 4
gpt4 key购买 nike

我最难弄清楚如何做到这一点(看起来很简单)。

我有一个 Javascript 对象,如下所示

console.log(data) 的输出:

{"prevExists":false,"pubKey":"b5","ID":"5f1"}

我正在尝试访问不同的键值对。

当我尝试预期的方法时,我返回未定义。

我试过:

var pubKey = "pubKey";
data.pubKey
data[pubkey];
data["pubKey"];

我知道我在这里遗漏了一些非常明显的东西。

最佳答案

您可以通过多种方式访问​​ key ,具体取决于您所谈论的 key 。

在您的示例中,任何一个都可以:

var data = {
"prevExists":false,
"pubKey":"b5",
"ID":"5f1"
};

// Access all keys of enumerable string-keyed properties
Object.keys(data).forEach((key) => console.log(key,data[key]));
// Access all keys of enumerable and non-enumerable string-keyed properties
Object.getOwnPropertyNames(data).forEach((key) => console.log(key,data[key]));
// Access all keys of enumerable string-keyed properties of your object, its prototype, and all the prototype chain...
for (let key in data)
console.log(key,data[key]);

如果您想更好地了解什么是对象的属性,可以查看this recent answer。我写了这个主题。

关于javascript - 访问 Javascript 对象键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48633717/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com