如何在不从函数声明变量的情况下 return 解构对象?

How to return a destructured object without declaring variable from a function?

const obj = {
  '0': '100',
  '1': '0',
  '2': '0'
};

console.log("defaultObj", obj);

const test1 = () => {
  return {
    0: amount,
    1: balance,
    2: products
  } = obj;
};

const test2 = () => {
  const {
    0: amount,
    1: balance,
    2: products
  } = obj;
  return {
    amount,
    balance,
    products
  }
};

console.log("test1", test1());
console.log("test2", test2());

输出为

defaultObj { '0': '100', '1': '0', '2': '0' }
test1 { '0': '100', '1': '0', '2': '0' }
test2 { amount: '100', balance: '0', products: '0' }

那么test1和test2有什么区别呢?

如何 return 一个解构的对象而不像在 test2 中那样将它们声明为变量。

所需的输出是通过立即return解构对象

将 test1 输出转换为 test2

不将它们声明为变量是否有可能的解决方案

what is the difference between test1 and test2?

赋值表达式总是return右边的值。 return (… = obj2) 将始终 return obj2 值,无论 是什么。

how to return a destructured object without declaring them as variables?

您似乎对解构的作用感到困惑。没有“解构对象”这样的东西,当你解构对象时,它就不再是对象了。它的个别部分被分配给普通变量。

在您的 test2 函数中,您然后使用具有 shorthand 语法的对象文字使用这些变量的值创建一个新对象。

无法将解构目标和对象字面量组合成一个表达式。

如果您不想通过解构引入单个变量(无论是在参数声明中还是单独的变量声明中),只需像往常一样直接访问参数对象属性:

function test3(obj) {
  return { amount: obj[0], balance: obj[1], products: obj[2] };
}

(摘自@user3840170 的评论)