无需辅助函数与try..catch,处理空值/未定义字符串trim的替代方法问询
Great question! Your current approach (obj.postcode || "").trim() is totally solid, but there are a few other idiomatic ways to achieve the same goal while sticking to your constraints. Let's break them down:
1. Nullish Coalescing Operator (??)
If you want to be more precise about only handling null/undefined (and not other falsy values like empty strings or 0), swap || with the nullish coalescing operator:
const postcode = (obj.postcode ?? "").trim();
Unlike ||, ?? only falls back to the empty string when obj.postcode is strictly null or undefined. This is safer if your postcode could ever be a falsy value you still want to trim (like " 0 ").
2. Conditional (Ternary) Operator
A more explicit approach that leaves your intent crystal clear for anyone reading the code:
const postcode = obj.postcode ? obj.postcode.trim() : "";
This checks if obj.postcode is truthy first—if it is, we trim it; otherwise, we use an empty string. Note that like your original || approach, this treats falsy values (like "" or 0) as "empty" and returns "".
3. Optional Chaining + Nullish Coalescing
Combine optional chaining with nullish coalescing for a concise, precise take:
const postcode = obj.postcode?.trim() ?? "";
Here, obj.postcode?.trim() returns undefined if obj.postcode is null/undefined (instead of throwing an error), and ?? "" replaces that undefined with an empty string. This avoids calling trim() on non-existent properties entirely, which is a nice guardrail.
Quick Note on Your Original Approach
Your initial method (obj.postcode || "").trim() works perfectly for most cases—it's concise and widely compatible. The alternatives above just offer tradeoffs in precision or readability, depending on your specific use case.
内容的提问来源于stack exchange,提问作者Hedge

