在JavaScript中获取JSON对象的值,通常是通过点(.
)表示法或者方括号([]
)表示法来实现的。
基础概念:
obj.property
。obj['property']
。示例代码:
假设有以下JSON对象:
let jsonObject = {
"name": "John",
"age": 30,
"city": "New York"
};
使用点表示法获取值:
let name = jsonObject.name; // "John"
let age = jsonObject.age; // 30
let city = jsonObject.city; // "New York"
使用方括号表示法获取值(例如,当属性名存储在变量中时):
let propertyName = "name";
let name = jsonObject[propertyName]; // "John"
常见问题及解决方法:
undefined
。为了避免这种情况,可以在访问之前进行检查。if (jsonObject.hasOwnProperty('nonExistentProperty')) {
let value = jsonObject.nonExistentProperty;
} else {
console.log('Property does not exist');
}
或者使用可选链操作符(?.
),这是ES2020引入的新特性:
let value = jsonObject?.nonExistentProperty; // undefined,不会报错
let jsonObject = {
"first-name": "John",
"last name": "Doe"
};
let firstName = jsonObject['first-name']; // "John"
let lastName = jsonObject['last name']; // "Doe"
let propertyName = prompt("Enter a property name:");
let value = jsonObject[propertyName]; // 根据用户输入获取值
优势:
领取专属 10元无门槛券
手把手带您无忧上云