什么是强制转换和解构param的JavaScript语法?

问题描述 投票:2回答:2

这似乎是一个愚蠢的问题。假设我有一个接受对象的函数。我如何将该对象转换为props,还将props.id解构为id(在参数声明中)?

function go ({ id }) {
  const props = arguments[0]; // how to do this with destructure?
  console.log('props', props, 'id', id);
}

go({id: 2});
javascript object ecmascript-6 destructuring object-destructuring
2个回答
4
投票

你不能这样做 - 只需保持props作为参数,以使这个代码更简单,更容易阅读:

function go (props) {
  const { id } = props;
  console.log('props', props, 'id', id);
}

go({id: 2});

3
投票

您可以遵循这种方法,将param命名为支持提取Id值的参数的道具和结构。

当您需要传递额外的参数时,问题就出现了。

function go (props, {id} = props) {
  //const props = arguments[0]; // how to do this with destructure?
  console.log('props', props, 'id', id);
}

go({id: 2});
© www.soinside.com 2019 - 2024. All rights reserved.