You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何安全简洁地输出可能未定义的root对象的uri属性?

Safely and Cleanly Output root.uri

Great question! Dealing with optional properties or potentially undefined values is a super common scenario in JavaScript, and there are a couple of clean, safe approaches to solve this based on your environment.

1. Use Optional Chaining (ES2020+)

This is the most concise and modern solution, widely supported in modern browsers and Node.js (v14+). The optional chain operator (?.) safely accesses the uri property only if root exists (is not undefined or null). If not, it returns undefined instead of throwing an error:

console.log('root.uri = ' + root?.uri);

If you want a friendly fallback instead of undefined when uri is missing, pair it with the nullish coalescing operator (??):

console.log('root.uri = ' + (root?.uri ?? 'URI not available'));

Unlike ||, ?? only falls back if the left-hand side is undefined or null—it won't trigger for valid falsy values like 0 or empty strings.

2. Compatibility-Friendly Short-Circuit Check

If you need to support older environments without ES2020 features, use a logical short-circuit to verify root exists before accessing uri:

console.log('root.uri = ' + (root && root.uri || 'URI not available'));

This works because && stops evaluating if root is falsy (like undefined), avoiding the "Cannot read property 'uri' of undefined" error. The || then provides a fallback if either root or root.uri is falsy.

Quick Context Fit

Since root is assigned either resolvedRoot or the result of an await call, the optional chain approach is perfect here—it handles both cases where resolvedRoot might be undefined, or the resolved value from getCurrentUserHome() lacks an uri property.

内容的提问来源于stack exchange,提问作者Socrates

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 09:40:15