首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

变量!.property和variable?.property是什么意思?JS TS?

在JavaScript和TypeScript中,.property和?.property都是用于访问对象属性的语法。

  1. .property:这是常规的属性访问语法,用于访问对象的属性。例如,如果有一个对象person,可以使用person.name来访问其name属性的值。
  2. ?.property:这是可选链操作符(Optional Chaining Operator),用于安全地访问对象的属性,特别是在处理可能为null或undefined的对象时非常有用。如果对象为null或undefined,使用?.property将返回undefined而不会引发错误。例如,如果有一个可能为null的对象person,可以使用person?.name来安全地访问其name属性的值。

示例代码:

代码语言:txt
复制
// JavaScript示例
var person = {
  name: "John",
  age: 30
};

console.log(person.name);  // 输出: John
console.log(person?.name); // 输出: John

var nullPerson = null;
console.log(nullPerson?.name); // 输出: undefined

// TypeScript示例
interface Person {
  name: string;
  age: number;
}

var person: Person = {
  name: "John",
  age: 30
};

console.log(person.name);  // 输出: John
console.log(person?.name); // 输出: John

var nullPerson: Person | null = null;
console.log(nullPerson?.name); // 输出: undefined

推荐的腾讯云相关产品和产品介绍链接地址:

  • 云函数(Serverless):https://cloud.tencent.com/product/scf
  • 云数据库 MongoDB 版:https://cloud.tencent.com/product/cosmosdb-mongodb
  • 云存储(对象存储):https://cloud.tencent.com/product/cos
  • 人工智能平台(AI Lab):https://cloud.tencent.com/product/ai
  • 物联网开发平台(IoT Explorer):https://cloud.tencent.com/product/iotexplorer
  • 腾讯云区块链服务(Tencent Blockchain):https://cloud.tencent.com/product/tbc
  • 腾讯云游戏多媒体引擎(GME):https://cloud.tencent.com/product/gme
  • 腾讯云音视频处理(VOD):https://cloud.tencent.com/product/vod
页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

  • 领券