1

我正在尝试嵌套这些解构赋值,以便分别初始化为context1和:context2market[pair.context]market[pair.target]

// set market to this[pair.market] or empty object
const {
  [pair.market]: market = {},
} = this; 

// set context1 to market[pair.context] or empty object
// set context2 to market[pair.target] or empty object
const {
  [pair.context]: context1 = {},
  [pair.target]: context2 = {},
} = market;

我认为这种正确的方法是这样的:

const {
  [pair.context]: context1 = {},
  [pair.target]: context2 = {},
} = {
  [pair.market]: market = {},
} = this;

但是,当market[pair.context]market[pair.target]已经存在时,它的行为似乎并不像预期的那样。

我对解构还很陌生,但我决心掌握它。为什么会这样,我如何结合前两个解构?


测试相关代码:

const pair1 = {
  context: 'A',
  target: 'B',
  market: 'MARKET1',
  price: '0.1',
};
const pair2 = {
  context: 'A',
  target: 'C',
  market: 'MARKET1',
  price: '1',
};
const pair3 = {
  context: 'C',
  target: 'B',
  market: 'MARKET2',
  price: '0.1',
};

// markets
function addPair (pair) {
  const {
    [pair.market]: market = {},
  } = this;

  const {
    [pair.context]: context1 = {},
    [pair.target]: context2 = {},
  } = market;

  this[pair.market] = {
    ...market,
    [pair.context]: {
      ...context1,
      [pair.target]: {
        price: +(pair.price),
      },
    },
    [pair.target]: {
      ...context2,
      [pair.context]: {
        price: +(1 / pair.price),
      },
    },
  };
}

const markets = {};

addPair.call(markets, pair1);
addPair.call(markets, pair2);
addPair.call(markets, pair3);

console.log(markets);
4

2 回答 2

3
于 2018-01-07T06:23:44.340 回答
2

使用Babel playground,我们可以看到代码在功能上是如何等效的。我已经简化了你的例子:

const {
  [pair.context]: context1 = {},
} = {
  [pair.market]: market = {},
} = markets;

被编译为

var _markets, _markets$pair$market;

var _pair$market = (_markets = markets, _markets$pair$market = _markets[pair.market], market = _markets$pair$market === undefined ? {} : _markets$pair$market, _markets),
    _pair$market$pair$con = _pair$market[pair.context],
    context1 = _pair$market$pair$con === undefined ? {} : _pair$market$pair$con;

这有点令人费解,但您可以看到以下作业正在进行:

_markets = markets;
_pair$market = _markets;
_pair$market$pair$con = _pair$market[pair.context]
context1 = _pair$market$pair$con

所以你的代码

const {
  [pair.context]: context1 = {},
  [pair.target]: context2 = {},
} = {
  [pair.market]: market = {},
} = this;

本质上是以下作业:

const market = this[pair.market];
const context1 = this[pair.context];
const context2 = this[pair.target];

这不是你想要的。

恐怕你必须把它分成两行。它也更容易阅读。放在一行中并让人们为试图理解该陈述而挠头并没有真正的价值。

于 2018-01-07T06:32:59.553 回答