JavaScript函数参数规范化:是否需要复制参数?
Great call thinking about avoiding mutation of the original argument—this is exactly the kind of defensive practice that saves you from hours of debugging weird side effects later!
Let’s break down why your approach works so well, and confirm it’s on the right track:
Why mutating the original argument is a problem
When you modify the input arg directly (like pushing to it or reassigning it), if that argument was a reference type (like an array or object) created outside your function, you’ll be altering the original value in the outer scope. This leads to unexpected behavior that’s super hard to trace, especially in larger codebases.
Your solution is solid
Your implementation correctly creates a safe, isolated copy of the input to work with:
const foo = (arg) => { const _arg = Array.isArray(arg) ? [...arg] : [arg]; // Now do_something with _arg, no risk to the original arg do_something(_arg); };
Here’s what’s happening step by step:
- If
argis already an array, the spread operator[...arg]creates a shallow copy of the array. This means you can modify_arg(like adding/removing elements) without touching the original array passed in. - If
argis any other type (string, number, object, etc.), you wrap it in an array sodo_somethingcan consistently handle an array input, no matter what was passed in.
Optional edge case handling (if needed)
If your function might receive null or undefined as input, you can adjust the logic to handle those gracefully too:
const foo = (arg) => { const _arg = arg == null ? [] : Array.isArray(arg) ? [...arg] : [arg]; do_something(_arg); };
This ensures _arg is always an array—even if the input is missing entirely.
Final takeaway
Your approach is exactly what we recommend for parameter normalization: it’s safe, clear, and avoids unintended side effects. Keep up the good habit of working with copies instead of mutating original inputs!
内容的提问来源于stack exchange,提问作者Leo Li

