gpt4 book ai didi

Javascript对象未定义问题

转载 作者:行者123 更新时间:2023-11-28 16:46:49 24 4
gpt4 key购买 nike

我在这里有点困惑。有人可以告诉我为什么这有效吗:

var selectedAttrs = {"mattress_size_variation":{"displayName":"Mattress Size","value":"King","displayValue":"King"},"mattress_feel_variation":{"displayName":"Mattress Feel","value":"Soft","displayValue":"Soft"}};

var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();

//Returns "King"

但这不会并引发错误?

var selectedAttrs = {"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}};

var selectedAttributes = JSON.parse(selectedAttrs);
return selectedAttributes.mattress_size_variation.value.toLowerCase();

TypeError: Cannot read property "value" from undefined

有什么区别,我应该如何从最后一个获得值?我假设我需要进行某种检查,因为一个可以工作,而另一个则不能。

最佳答案

第二个 JSON 中有一个未 trim 的空格,因此您必须使用方括号访问该属性:

selectedAttributes['mattress_size_variation ']

var selectedAttrs = '{"mattress_size_variation ":{"displayName":"Mattress Size","value":"Twin","displayValue":"Twin"}}'

var selectedAttributes = JSON.parse(selectedAttrs);
console.log(selectedAttributes['mattress_size_variation '].value);

关于Javascript对象未定义问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60461166/

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